当我运行以下代码时:
url = 'http://www.nytimes.com/2011/11/15/arts/music/new-music-from-caveman-los-campesinos-and-the-fall.html?_r=0'
try:
handle = urllib2.urlopen(url).info()
except urllib2.HTTPError, e:
print(e.code)
出现错误,print e.code
打印出 303
。
如果我使用 Chrome 或 Firefox 请求此 URL,它工作正常。
有人可以帮忙吗? 谢谢
最佳答案
您需要处理重定向,因为 HTTP 303 is a "See Other"回复。内容所在的位置将在 Location
header 中提供给您:
>>> e.headers['Location']
'http://www-nc.nytimes.com/2011/11/15/arts/music/new-music-from-caveman-los-campesinos-and-the-fall.html?=_r=6&'
现在,今天使用 urllib
/urllib2
真的是自找苦吃,你真正应该做的是使用优秀的 requests
图书馆,它将为您处理一切。
我认为我们可以说使用 requests
是在 Python 中执行 HTTP 的正确方法:
>>> res = requests.get(url)
<Response [200]>
>>> print res.text
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" # And so on
关于python - 如何在 Python 2.7 中处理 Httperror 303?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13862716/