简体   繁体   English

Cookie是否在打​​开URL之间保留在Mechanize浏览器中?

[英]Are cookies kept in a Mechanize browser between opening URLs?

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? 我的问题是:是否需要管理Mechanize浏览器中的 cookie,还是需要设置CookieJar或其他内容,还是为您跟踪所有cookie?

The first example here talks about cookies being carried between requests, but they don't talk about browsers. 这里的第一个示例讨论的是在请求之间携带cookie,但它们没有讨论浏览器。

Yes you will have to store the cookie between open requests in mechanize . 是的,您将不得不在mechanize open请求之间存储cookie 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. 可以执行以下操作,因为您可以将cookiejar添加到br对象中,并且只要该对象存在,它就会维护该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 . 我使用perl mechanize很多,但是没有使用python所以我可能错过了一些特定于python工具来工作,所以如果我道歉,我不想简单地用yes回答。

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

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