[英]What is mechanize.CookieJar() in mechanize Python?
I've recently been working on a script that accesses a website's form to log in. Tried with requests but it seems that mechanize works better for this application. 我最近一直在研究一种脚本,该脚本可以访问网站的表单进行登录。尝试了请求,但是机械化似乎对该应用程序更好。 Was asking around and I wrote this code which does work:
到处问,我写了下面的代码,它可以正常工作:
mCookieJar = mechanize.CookieJar()
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_equiv(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Manjaro; U; Linux x86_64; en-US; rv:1.9.0.1)')]
br.set_cookiejar(mCookieJar)
br.open(LoginUrl)
br.select_form(action="/takelogin.php")
br['email'] = Username
br['password'] = Password
resp = br.submit()
This works fine, but it creates a new session cookie every time the script is run. 这可以正常工作,但是每次运行脚本时都会创建一个新的会话cookie。 This is not ideal as in my user preferences for this website, I end up with a HUGE list of sessions that I need to manually close.
这是不理想的,因为按照我对该网站的用户偏好设置,我最终需要手动关闭大量会话。 The website does have another way around this for automated scripts - you can generate a permanent cookie just for this purpose.
该网站对于自动脚本确实有另一种解决方法-您可以为此目的生成一个永久cookie。
However, I have no idea what mechanize.CookieJar() is. 但是,我不知道是什么机械化。CookieJar()是什么 。 I can't find any mention of this method or class in the Python mechanize documentation .
在Python机械化文档中找不到该方法或类的任何提及。 There are a couple different cookiejar libs out there, but I don't need to include any of them for this to work.
那里有几个不同的cookiejar库,但是我不需要包括其中的任何一个都可以使它起作用。
So what is this class? 那这堂课是什么? Is it part of mechanize?
是机械化的一部分吗? How can I manually add cookies to it?
如何手动向其中添加Cookie? There are some set_cookie() methods for the mechanize.Browser() class but I have no idea if these automatically add them to the active cookiejar.
mechanize.Browser()类有一些set_cookie()方法,但我不知道这些方法是否会自动将它们添加到活动cookiejar中。 It seems very strange to me that this code works, and there are examples online using mechanize.CookieJar(), yet there is no mention of this anywhere in the documentation.
对于我来说,这段代码可以工作很奇怪,并且在网上有使用mechanize.CookieJar()的示例,但是在文档中没有任何提及。
Browsing through the source it seems like mechanize
is re-exporting CookieJar
from either cookielib
(Python2) or http.cookiejar
(Python3). 浏览源代码似乎是
mechanize
它CookieJar
从cookielib
(Python2)或http.cookiejar
(Python3)中重新导出CookieJar
。
Having that said, if you want to persist your cookie across different runs of the script you should probably be using FileCookieJar
instead. 话虽如此,如果您想在脚本的不同运行之间持久保存cookie,则可能应该使用
FileCookieJar
。 This also gets re-exported the same way: 这也将以相同的方式重新导出:
cookielib.FileCookieJar
(Python2) cookielib.FileCookieJar
(Python2) http.cookiejar.FileCookieJar
(Python3) http.cookiejar.FileCookieJar
(Python3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.