How to save mechanize.Browser() cookies to file?

和自甴很熟 提交于 2020-01-13 04:40:25

问题


How could I make Python's module mechanize (specifically mechanize.Browser()) to save its current cookies to a human-readable file? Also, how would I go about uploading that cookie to a web page with it?

Thanks


回答1:


Deusdies,I just figured out a way with refrence to Mykola Kharechko's post

#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()



回答2:


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

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)



回答3:


The CookieJar has several subclasses that can be used to save cookies to a file. For browser compatibility use MozillaCookieJar, for a simple human-readable format go with LWPCookieJar, just like this (an authentication via 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()


来源:https://stackoverflow.com/questions/7510806/how-to-save-mechanize-browser-cookies-to-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!