我有一个让我发疯的问题。我正在使用urllib2来获取很多网址。有一个url有时会返回给我整个html页面,有时不会。这是我的代码:
def find_html(url):
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
page_html = urllib2.urlopen(req).read()
n = string.find(page_html, "filter clearfix active")
print "find element:",n
url = "http://it.hotels.com/ho113127/rome-cavalieri-waldorf-astoria-hotels-resorts-roma-italia/"
find_html(url)为什么会发生这种情况?我哪里做错了?(对于这个url,我不想使用selenium,我想使用urllib2)
发布于 2013-03-13 19:29:08
我从这个网址得到了200和301 (Moved Permanently)的响应,所以这是一个服务器的问题。
因为urllib2会自动跟踪重定向,所以如果你想阻止处理重定向的页面(如果我理解正确的话,它不包含你想要的信息),你必须检查是否发生了重定向:
...
response = urllib2.urlopen(req)
if response.geturl() == url:
// no redirect occurred
else:
// a redirect occurred because the url has changed这取决于您的确切设置和意图,您必须如何处理它(因为对于某些URL,您可能实际上想要处理重定向的页面)。
https://stackoverflow.com/questions/15383935
复制相似问题