如何将 cookie 添加到 Python 中现有的 cookielib CookieJar 实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2169281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:57:46  来源:igfitidea点击:

How to add cookie to existing cookielib CookieJar instance in Python?

pythoncookiesmechanizecookiejarcookielib

提问by Paul

I have a CookieJar that's being used with mechanize that I want to add a cookie to. How can I go about doing this? make_cookie() and set_cookie() weren't clear enough for me.

我有一个与机械化一起使用的 CookieJar,我想向其中添加 cookie。我该怎么做呢?make_cookie() 和 set_cookie() 对我来说还不够清楚。

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

回答by Paul

Managed to figure this out

设法解决了这个问题

import mechanize
import cookielib
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
ck = cookielib.Cookie(version=0, name='Name', value='1', port=None, port_specified=False, domain='www.example.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
cj.set_cookie(ck)
for index, cookie in enumerate(cj):
    print index, ' : ', cookie

Output:

输出:

0  :  <Cookie Name=1 for www.example.com/>