Python3 urllib.request会自动重定向301/302,如何禁用此行为?
答案 0 :(得分:1)
库“ requests”使它变得更容易,但是如果您需要或想要使用urllib.request,则可以:
from urllib import request
import urllib.error
class NoRedirect(request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
opener = request.build_opener(NoRedirect)
request.install_opener(opener)
try:
r = request.urlopen('http://google.com')
except urllib.error.HTTPError as e:
r = e
print(r.status)
print(dir(r))