在打开URL之间,Cookie是否保留在Mechanize浏览器中? [英] Are cookies kept in a Mechanize browser between opening URLs?

查看:91
本文介绍了在打开URL之间,Cookie是否保留在Mechanize浏览器中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的代码:

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

但是,我的脚本正在响应,好像它没有针对第二个请求登录.我检查了第一个请求,是的,它成功登录.我的问题是:是否需要管理机械化浏览器中的cookie,还是需要设置CookieJar或其他工具,还是为您跟踪所有cookie?

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?

第一个示例此处讨论了在请求之间携带cookie,但它们并没有不要谈论浏览器.

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

推荐答案

是的,您将必须在mechanize中的open个请求之间存储cookie.可以使用类似于以下内容的方法,因为您可以将cookiejar添加到br对象,并且只要该对象存在,它就可以保持该cookie.

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.

我大量使用了perl mechanize,但没有使用python,所以我可能错过了一些特定的python来解决这个问题,所以如果我道歉,我不想简单地回答. yes.

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.

这篇关于在打开URL之间,Cookie是否保留在Mechanize浏览器中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆