我正在尝试使用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>
但是当我在浏览器中打开这个网址时工作正常 这是网址
http://1033kissfm.com
在浏览器中重定向到
http://www.1033kissfm.com/pages/main
页。
答案 0 :(得分:0)
我解决了这个问题,因为我认为库不提供任何处理重定向的支持。此代码将有助于找到重定向以获取正确的响应
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 hops