如何在Python2.7中处理Httperror 303?

2024-09-27 23:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行以下代码时:

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,它可以正常工作。在

有人能帮忙吗? 谢谢


Tags: 代码fromcomhttpurlnewwwwmusic
2条回答

303是重定向。你的浏览器会自动处理它,urllib2需要一些诱饵。在

请看下面的解释:

http://www.diveintopython.net/http_web_services/redirects.html

您将需要处理重定向,因为HTTP 303 is a "See Other"响应。内容所在的位置将显示在Location标题中:

>>> 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是在Python中执行HTTP的正确方法:

^{pr2}$

相关问题 更多 >

    热门问题