Python Mechanize阻止连接:关闭

时间:2013-02-04 19:14:40

标签: python mechanize

我正在尝试使用mechanize从网页获取信息。它基本上取得了第一部分信息的成功,但网页包含一个“下一步”按钮以获取更多信息。我无法弄清楚如何以编程方式获取其他信息。

通过使用Live HTTP Headers,我可以看到当我单击浏览器中的下一个按钮时生成的http请求。似乎我可以使用mechanize发出相同的请求,但在后一种情况下,我没有进入下一页,而是被重定向到网站的主页。

显然,机械化正在做一些与浏览器不同的事情,但我无法弄清楚是什么。在比较标题时,我确实发现了一个区别,即使用的浏览器

连接:保持活力

使用机械化时

连接:关闭

我不知道这是否是罪魁祸首,但当我尝试添加标题('Connection','keep-alive')时,它没有改变任何内容。

[UPDATE] 当我在Firefox中单击“第2页”按钮时,生成的http是(根据实时HTTP标头):

GET /statistics/movies/ww_load/the-fast-and-the-furious-6-2012?authenticity_token=ItU38334Qxh%2FRUW%2BhKoWk2qsPLwYKDfiNRoSuifo4ns%3D&facebook_fans_page=2&tbl=facebook_fans&authenticity_token=ItU38334Qxh%2FRUW%2BhKoWk2qsPLwYKDfiNRoSuifo4ns%3D HTTP/1.1
Host: www.boxoffice.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0
Accept: text/javascript, text/html, application/xml, text/xml, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
X-Prototype-Version: 1.6.0.3
Referer: http://www.boxoffice.com/statistics/movies/the-fast-and-the-furious-6-2012
Cookie: __utma=179025207.1680379428.1359475480.1360001752.1360005948.13; __utmz=179025207.1359475480.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __qca=P0-668235205-1359475480409; zip=13421; country_code=US; _boxoffice_session=2202c6a47fc5eb92cd0ba57ef6fbd2c8; __utmc=179025207; user_credentials=d3adbc6ecf16c038fcbff11779ad16f528db8ebd470befeba69c38b8a107c38e9003c7977e32c28bfe3955909ddbf4034b9cc396dac4615a719eb47f49cc9eac%3A%3A15212; __utmb=179025207.2.10.1360005948
Connection: keep-alive

当我尝试在mechanize中请求相同的url时,它看起来像这样:

GET /statistics/movies/ww_load/the-fast-and-the-furious-6-2012?facebook_fans_page=2&tbl=facebook_fans&authenticity_token=ZYcZzBHD3JPlupj%2F%2FYf4dQ42Kx9ZBW1gDCBuJ0xX8X4%3D HTTP/1.1
Accept-Encoding: identity
Host: www.boxoffice.com
Accept: text/javascript, text/html, application/xml, text/xml, */*
Keep-Alive: 115
Connection: close
Cookie: _boxoffice_session=ced53a0ca10caa9757fd56cd89f9983e; country_code=US; zip=13421; user_credentials=d3adbc6ecf16c038fcbff11779ad16f528db8ebd470befeba69c38b8a107c38e9003c7977e32c28bfe3955909ddbf4034b9cc396dac4615a719eb47f49cc9eac%3A%3A15212
Referer: http://www.boxoffice.com/statistics/movies/the-fast-and-the-furious-6-2012
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1

- 达里尔

2 个答案:

答案 0 :(得分:1)

服务器正在检查X-Requested-With和/或X-Prototype-Version,因此将这两个标头添加到机械化请求中会修复它。

答案 1 :(得分:0)

也许有点迟到的答案,但我通过在_urllib2_forked.py中添加一行来解决这个问题

第1098行的

代表:headers["Connection"] = "Close"

将其更改为:

if not 'Connection' in headers: headers["Connection"] = "Close" 并确保在脚本中设置标题,它将起作用。

的Gr。 Squandor

相关问题