简体   繁体   English

如何保存mechanize.Browser()cookie到文件?

[英]How to save mechanize.Browser() cookies to file?

How could I make Python's module mechanize (specifically mechanize.Browser()) to save its current cookies to a human-readable file? 我怎样才能使Python的模块机械化(特别是mechanize.Browser())将其当前的cookie保存到人类可读的文件中? Also, how would I go about uploading that cookie to a web page with it? 另外,我如何将该cookie上传到带有它的网页?

Thanks 谢谢

Deusdies,I just figured out a way with refrence to Mykola Kharechko's post Deusdies,我只是想出了一种赞成Mykola Kharechko的帖子

#to save cookie
>>>cookiefile=open('cookie','w')
>>>cookiestr=''
>>>for c in br._ua_handlers['_cookies'].cookiejar:
>>>    cookiestr+=c.name+'='+c.value+';'
>>>cookiefile.write(cookiestr)  
#binding this cookie to another Browser
>>>while len(cookiestr)!=0:
>>>    br1.set_cookie(cookiestr)
>>>    cookiestr=cookiestr[cookiestr.find(';')+1:]
>>>cookiefile.close()

If you want to use the cookie for a web request such as a GET or POST (which mechanize.Browser does not support), you can use the requests library and the cookies as follows 如果您想将cookie用于Web请求,例如GET或POST(mechanize.Browser不支持),您可以使用请求库和cookie,如下所示

import mechanize, requests

br = mechanize.Browser()
br.open (url)
# assuming first form is a login form
br.select_form (nr=0)
br.form['login'] = login
br.form['password'] = password
br.submit()
# if successful we have some cookies now
cookies = br._ua_handlers['_cookies'].cookiejar
# convert cookies into a dict usable by requests
cookie_dict = {}
for c in cookies:
    cookie_dict[c.name] = c.value
# make a request
r = requests.get(anotherUrl, cookies=cookie_dict)

The CookieJar has several subclasses that can be used to save cookies to a file. CookieJar有几个子类,可用于将cookie保存到文件中。 For browser compatibility use MozillaCookieJar , for a simple human-readable format go with LWPCookieJar , just like this (an authentication via HTTP POST): 对于浏览器兼容性,使用MozillaCookieJar ,对于简单的人类可读格式,请使用LWPCookieJar ,就像这样(通过HTTP POST进行身份验证):

import urllib
import cookielib
import mechanize

params = {'login': 'mylogin', 'passwd': 'mypasswd'}
data = urllib.urlencode(params)

br = mechanize.Browser()
cj = mechanize.LWPCookieJar("cookies.txt")
br.set_cookiejar(cj)
response = br.open("http://example.net/login", data)
cj.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM