Are cookies kept in a Mechanize browser between opening URLs?

放肆的年华 提交于 2020-01-16 01:20:29

问题


I have code similar to this:

br = mechanize.Browser()
br.open("https://mysite.com/")
br.select_form(nr=0)
#do stuff here
response = br.submit()
html = response.read()

#now that i have the login cookie i can do this...
br.open("https://mysite.com/")
html = response.read()

However, my script is responding like it's not logged in for the second request. I checked the first request and yes, it logs in successfully. My question is: do cookies in Mechanize browsers need to be managed or do I need to setup a CookieJar or something, or does it keep track of all of them for you?

The first example here talks about cookies being carried between requests, but they don't talk about browsers.


回答1:


Yes you will have to store the cookie between open requests in mechanize. Something similar to the below should work as you can add the cookiejar to the br object and as long as that object exists it maintains that cookie.

import Cookie
import cookielib
cookiejar =cookielib.LWPCookieJar()

br = mechanize.Browser()
br.set_cookiejar(cookiejar)
br.open("https://mysite.com/")
br.select_form(nr=0)
#do stuff here
response = br.submit()
html = response.read()

#now that i have the login cookie i can do this...
br.open("https://mysite.com/")
html = response.read()

The Docs cover it in more detail.

I use perl mechanize alot, but not python so I may have missed something python specific for this to work, so if I did I apologize, but I did not want to answer with a simple yes.



来源:https://stackoverflow.com/questions/23840374/are-cookies-kept-in-a-mechanize-browser-between-opening-urls

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