[英]urllib2 Request issue
我正在尝试使用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时,它的工作正常
http://1033kissfm.com
在浏览器中,它重定向到
http://www.1033kissfm.com/pages/main
页。
我解决了这个问题,因为我认为图书馆不提供任何处理重定向的支持。 此代码将有助于找到重定向以获取正确的响应
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.