python - 如何在 Python 2.7 中处理 Httperror 303?

标签 python redirect urllib2

当我运行以下代码时:

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/

相关文章:

python:导入失败时的库行为

python - 构造函数及使用方法

url - 登录失败时将用户从 Moodle 重定向到另一个站点

php - 302 重定向是如何发生的?

python - 通过代理安装 python 模块

php - Python POST 文件到 PHP

python加载json数据错误

Python:记录到多个日志文件

redirect - Django : At the view level, 我可以将 'noindex' header 添加到 'redirect' 响应中吗?

python - 在 Linux 上使用 Python 以编程方式提供辅助 WiFi 热点凭证