Python:如何转储 mechanize.Browser 实例的 cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/606072/
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
Python: how to dump cookies of a mechanize.Browser instance?
提问by Anonymous
I am learning how to use mechanize, a Python module to automate interacting with websites.
我正在学习如何使用mechanize,一个 Python 模块来自动与网站交互。
One feature is the automated handling of cookies. I would to want to dump cookies from a mechanize.Browser
instance for debugging purposes, but I can't seem to figure this out myself.
一项功能是自动处理 cookie。我想从mechanize.Browser
实例中转储 cookie 以进行调试,但我自己似乎无法弄清楚。
回答by Mykola Kharechko
>>> from mechanize import Browser
>>> b = Browser()
>>> b._ua_handlers['_cookies'].cookiejar
mechanize._clientcookie.CookieJar[]
>>> b.open('http://google.com')
response_seek_wrapper at 0xb7a922ccL whose wrapped object = closeable_response at 0xb7aa070cL whose fp = socket._fileobject object at 0xb7a94224
>>>
>>> b._ua_handlers['_cookies'].cookiejar
mechanize._clientcookie.CookieJar[Cookie(version=0, name='PREF', value='ID=57d545c229b4cf3f:TM=1236081634:LM=1236081634:S=p001WJMOr-V8Rlvi', port=None, port_specified=False, domain='.google.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153634, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False), Cookie(version=0, name='PREF', value='ID=20534d80a5ccf2ea:TM=1236081635:LM=1236081635:S=jW3UotZ0dg8sv6mf', port=None, port_specified=False, domain='.google.com.ua', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153635, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False)]
>>>
回答by Afsar Ahmad
Just print the CookieJar Instance
只需打印 CookieJar 实例
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Dump
print cj
回答by Eduardo
Mykolas' answer almost gave me what I was looking for. I was looking for how to save the cookie to a file. Since this answer gives margin to dumping the cookie into a file, maybe it is going to be useful for other people coming here looking for that. To save the cookie to a file:
Mykolas 的回答几乎给了我想要的东西。我正在寻找如何将 cookie 保存到文件中。由于此答案为将 cookie 转储到文件中提供了余地,因此它可能对其来这里寻找它的其他人有用。要将 cookie 保存到文件:
br._ua_handlers['_cookies'].cookiejar.save("cookie.txt", ignore_discard=True, ignore_expires=True)