【发布时间】:2012-11-25 04:13:35
【问题描述】:
我需要在需要 cookie 的网页上填写登录表单并获取有关结果页面的一些信息。由于这需要在晚上非常奇怪的时间完成,我想自动化这个过程,因此我使用机械化(欢迎任何其他建议 - 请注意,我必须在学校服务器上运行我的脚本,我不能安装新软件。Mechanize 是纯 python,所以我能够解决这个问题)。
问题是托管登录表单的页面要求我能够接受和发送 cookie。理想情况下,我希望能够接受和发送服务器发送给我的所有 cookie,而不是硬编码我自己的 cookie。
所以,我开始使用 mechanize 编写脚本,但我似乎处理 cookie 错误。由于我在任何地方都找不到有用的文档(如果我是盲人请指出),我在这里问。
这是我的机械化脚本:
import mechanize as mech
br = mech.Browser()
br.set_handle_robots(False)
print "No Robots"
br.set_handle_redirect(True)
br.open("some internal uOttawa website")
br.select_form(nr=0)
br.form['j_username'] = 'my username'
print "Login: ************"
br.form['j_password'] = 'my password'
print "Password: ************"
response = br.submit()
print response.read()
这会打印以下内容
No Robots
Login: ************
Password: ************
<html>
<body>
<img src="/idp/images/uottawa-logo-dark.png" />
<h3>ERROR</h3>
<p>
An error occurred while processing your request. Please contact your helpdesk or
user ID office for assistance.
</p>
<p>
This service requires cookies. Please ensure that they are enabled and try your
going back to your desired resource and trying to login again.
</p>
<p>
Use of your browser's back button may cause specific errors that can be resolved by
going back to your desired resource and trying to login again.
</p>
<p>
If you think you were sent here in error,
please contact technical support
</p>
</body>
</html>
如果我在 Chrome 浏览器上禁用 cookie 并尝试相同的操作,这确实是我会得到的页面。
我尝试如下添加一个 cookie jar,但没有成功。
br = mech.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
我查看了多个 mechanize 文档来源。 One of them提
A common mistake is to use mechanize.urlopen(), and the .extract_cookies() and
.add_cookie_header() methods on a cookie object themselves.
If you use mechanize.urlopen() (or OpenerDirector.open()),
the module handles extraction and adding of cookies by itself,
so you should not call .extract_cookies() or .add_cookie_header().
这似乎是说我的第一种方法应该有效,但它没有。
如果能提供任何帮助,我将不胜感激 - 这很令人困惑,而且似乎严重缺乏文档。
【问题讨论】:
-
如果可能的话,我会亲自使用
requests写这个——wwwsearch.sourceforge.net/mechanize/… 有帮助吗? (这似乎暗示传递一个开启者处理程序是必要的)(编辑:现在我在其他地方读到似乎与此相矛盾的......所以我倾向于同意文档!) -
@inspectorG4dget:你有解决办法吗?我正在寻找答案
-
@John:抱歉,没有。此外,大学将他们的网站更改为对脚本更友好的网站,所以我放弃了这个问题。对不起,我没能帮助你。如果您想要答案,您可以悬赏此问题以吸引其他用户回答。我可能会接受您授予赏金的答案
标签: python cookies mechanize shibboleth