Mechanize浏览器超时无效
我在使用 mechanize
的 timeout
功能时遇到了一些问题。大部分网页上这个功能都能正常工作,如果网址在合理的时间内没有加载出来,它就会报错:urllib2.URLError: <urlopen error timed out>
。不过,在某些网页上,这个计时器似乎失效了,程序甚至对键盘中断都没有反应。这里有一个出现这种情况的示例网页:
import mechanize
url = 'https://web.archive.org/web/20141104183547/http://www.dallasnews.com/'
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Firefox')]
html = br.open(url, timeout=0.01).read() #hangs on this page, timeout set extremely low to trigger timeout on all pages for debugging
首先,这个脚本在其他人访问这个特定网址时也会卡住吗?其次,可能出了什么问题,我该怎么调试呢?
1 个回答
-2
我不知道为什么用 mechanize 发出的这个网址请求会卡住,但用 urllib2 发出的请求就没问题。可能他们有一些代码能识别出 mechanize,尽管我们把机器人的设置改成了不允许。
我觉得 urllib2 应该是你这个情况的一个不错的解决方案。
import mechanize
import urllib2
url = 'https://web.archive.org/web/20141104183547/http://www.dallasnews.com/'
try:
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('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')]
html = br.open(url).read() #set_handle_robots
except:
req = urllib2.Request(url, headers={'User-Agent' : 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16'})
con = urllib2.urlopen( req )
html = con.read()
print html