在使用 Python 的 urllib
库时,如果你想防止它遵循 HTTP 重定向,可以通过自定义一个 HTTPRedirectHandler
来实现。你可以覆盖 HTTPRedirectHandler
的 http_error_302
和 http_error_301
方法,使其在遇到重定向时抛出异常或执行其他操作。
以下是一个示例,展示了如何防止 urllib
遵循重定向:
import urllib.request
import urllib.error
class NoRedirectHandler(urllib.request.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp)
def http_error_301(self, req, fp, code, msg, headers):
raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp)
# 创建一个自定义的 opener
opener = urllib.request.build_opener(NoRedirectHandler())
# 使用自定义的 opener 进行请求
url = 'http://example.com' # 替换为你要请求的 URL
try:
response = opener.open(url)
content = response.read()
print(content)
except urllib.error.HTTPError as e:
if e.code in (301, 302):
print(f"Redirect detected to {e.headers['Location']}")
else:
print(f"HTTP Error: {e.code} - {e.reason}")
except Exception as e:
print(f"Error: {e}")
在这个示例中,我们定义了一个 NoRedirectHandler
类,继承自 urllib.request.HTTPRedirectHandler
,并覆盖了 http_error_302
和 http_error_301
方法,使其在遇到 302 或 301 重定向时抛出 HTTPError
异常。
然后,我们使用 urllib.request.build_opener
创建一个自定义的 opener,并使用这个 opener 进行 HTTP 请求。如果请求过程中遇到重定向,程序会捕获到 HTTPError
异常,并输出重定向的目标 URL。
这样,你就可以防止 urllib
遵循重定向,并根据需要处理重定向的情况。
领取专属 10元无门槛券
手把手带您无忧上云