我正在尝试使用urllib2打开页面
req = urllib2.Request("http://1033kissfm.com",
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0'})
response = urllib2.urlopen(req)
rstPage = response.read()回应是
<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.0.3</center>
</body>
</html>但是当我在浏览器中打开这个url时,它工作正常,这就是url
http://1033kissfm.com在浏览器中,它重定向到
http://www.1033kissfm.com/pages/main页面。
发布于 2012-07-29 20:02:33
我解决了这个问题,因为我认为库不提供任何处理重定向的支持。此代码将帮助查找重定向以获取正确的响应
def get_hops(url):
redirect_re = re.compile('<meta[^>]*?url=(.*?)["\']', re.IGNORECASE)
hops = []
while url:
if url not in hops:
hops.insert(0, url)
response = urllib2.urlopen(url)
if response.geturl() != url:
hops.insert(0, response.geturl())
# check for redirect meta tag
match = redirect_re.search(response.read())
if match:
url = urlparse.urljoin(url, match.groups()[0].strip())
else:
url = None
return hopshttps://stackoverflow.com/questions/11708573
复制相似问题