Python 2.7 urllib2 在使用 xml 内容点击重定向时引发 urllib2.HTTPError 301

Python 2.7 urllib2 raising urllib2.HTTPError 301 when hitting redirect with xml content

我正在使用 urllib2 在 hxxp://s3.amazonaws.com/mybucket 请求特定的 S3 存储桶。亚马逊发回 HTTP 代码 301 以及一些 XML 数据(重定向到 hxxp://mybucket.s3.amazonaws.com/)。 python 没有遵循重定向,而是引发了 urllib2.HTTPError: HTTP Error 301: Moved Permanently.

根据 HOWTO Fetch Internet Resources Using urllib2 上的官方 Python 文档,"the default handlers handle redirects (codes in the 300 range)"。

是 python 处理不当(可能是因为响应中的意外 XML),还是我做错了什么?我在 Wireshark 中观看过,返回的响应与 python 的请求完全相同,就像它对我使用 Web 客户端所做的一样。在调试中,我没有看到 XML 在响应对象的任何地方被捕获。

感谢您的指导。

编辑:很抱歉最初没有发布代码。没什么特别的,字面意思就是这个 -

import urllib2, httplib

request = urllib2.Request(site)
response = urllib2.urlopen(request)

你最好使用 requests 库。 requests 默认处理重定向:http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history

import requests

response = requests.get(site)
print(response.content)

我不明白 urllib2 的问题,我试图查看文档 https://docs.python.org/2/library/urllib2.html 但它看起来不直观。

似乎在 Python3 中,他们对其进行了重构,使其使用起来负担更轻,但我仍然坚信 requests 是可行的方法。

Note The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.