Python Mechanize 防止 Connection:Close
我正在尝试使用 mechanize 从一个网页获取信息。基本上,我能成功获取到第一部分信息,但这个网页上有一个“下一页”的按钮,可以获取更多信息。我不知道怎么才能通过编程的方式获取这些额外的信息。
通过使用 Live HTTP Headers,我可以看到当我在浏览器中点击下一页按钮时生成的 http 请求。看起来我可以用 mechanize 发出同样的请求,但在这种情况下,我并没有得到下一页,而是被重定向到了网站的首页。
显然,mechanize 和我的浏览器做的事情不一样,但我搞不清楚是什么原因。在对比请求头时,我发现了一个不同之处,那就是使用的浏览器。
浏览器使用的是
Connection: keep-alive
而 mechanize 使用的是
Connection: close
我不知道这是否是问题所在,但当我尝试添加头信息('Connection','keep-alive')时,并没有改变什么。
[更新]
当我在 Firefox 中点击“第 2 页”按钮时,生成的 http 请求是(根据 Live HTTP Headers):
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
--
Daryl
2 个回答
也许我回答得有点晚,但我通过在 _urllib2_forked.py 文件中添加一行代码解决了这个问题。
在第1098行有这么一行代码:headers["Connection"] = "Close"
把它改成:
if not 'Connection' in headers:
headers["Connection"] = "Close"
确保你在脚本中设置了这个头信息,这样就能正常工作了。
祝好,Squandor
服务器在检查 X-Requested-With
和/或 X-Prototype-Version
这两个信息,所以在 mechanize 请求中加上这两个头信息就解决了问题。