Python urllib2.urlopen 返回302错误,尽管页面存在
我正在使用Python的函数urllib2.urlopen
来读取http://www.bad.org.uk/这个网站,但我总是遇到302错误,尽管我直接访问这个网站时一切正常。有人知道这是为什么吗?
import socket
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }
socket.setdefaulttimeout(10)
try:
req = urllib2.Request('http://www.bad.org.uk/', None, headers)
urllib2.urlopen(req)
return True # URL Exist
except ValueError, ex:
print 'URL: %s not well formatted' % 'http://www.bad.org.uk/'
return False # URL not well formatted
except urllib2.HTTPError, ex:
print 'The server couldn\'t fulfill the request for %s.' % 'http://www.bad.org.uk/'
print 'Error code: ', ex.code
return False
except urllib2.URLError, ex:
print 'We failed to reach a server for %s.' % 'http://www.bad.org.uk/'
print 'Reason: ', ex.reason
return False # URL don't seem to be alive
错误信息:
The server couldn't fulfill the request for http://www.bad.org.uk//site/1/default.aspx.
Error code: 302
2 个回答
3
代码302表示临时重定向,这意味着你需要从响应中的“位置”字段获取网址,然后去请求那个网址。
20
当禁用 cookies 时,http://www.bad.org.uk/ 这个页面会出现问题。
访问 http://www.bad.org.uk/ 时,会返回:
HTTP/1.1 302 Found
Location: http://www.bad.org.uk/DesktopDefault.aspx
Set-Cookie: Esperantus_Language_bad=en-GB; path=/
Set-Cookie: Esperantus_Language_rainbow=en-GB; path=/
Set-Cookie: PortalAlias=rainbow; path=/
Set-Cookie: refreshed=true; expires=Thu, 04-Nov-2010 16:21:23 GMT; path=/
Set-Cookie: .ASPXAUTH=; expires=Mon, 11-Oct-1999 23:00:00 GMT; path=/; HttpOnly
Set-Cookie: portalroles=; expires=Mon, 11-Oct-1999 23:00:00 GMT; path=/
如果我接着请求 http://www.bad.org.uk/DesktopDefault.aspx,而没有 设置这些 cookies,就会得到另一个 302 状态码,并且会重定向回自己。
urllib2
忽略了 cookies,发送的新请求没有携带 cookies,这就导致了在那个网址上出现了重定向循环。要解决这个问题,你需要添加一个 cookie 处理器:
import urllib2
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
response = opener.open('http://www.bad.org.uk')
print response.read()