如何使用仅限python的urllib库跟踪或检查重定向URL的历史记录
当您转到after 6重定向时,将导致如何使用仅限python的urllib库跟踪或检查重定向URL的历史记录,python,redirect,urllib,Python,Redirect,Urllib,当您转到after 6重定向时,将导致https://httpbin.org/get。我想检查两者之间的URL-仅使用python urllib.request import urllib.request def openurl(url): headers = {} req = urllib.request.Request(url, headers=headers) httpResponse = urllib.request.urlopen(req) cod
https://httpbin.org/get
。我想检查两者之间的URL-仅使用python urllib.request
import urllib.request
def openurl(url):
headers = {}
req = urllib.request.Request(url, headers=headers)
httpResponse = urllib.request.urlopen(req)
code = httpResponse.getcode()
httpHeader = httpResponse.info()
httpBody = httpResponse.read().decode()
return httpHeader, httpBody, code
url = 'https://httpbin.org/redirect/6'
h, b, c = openurl(url)
print(h)
print(b)
print('http Response Code:', c)
有没有办法调整urlopen的行为,以便生成介于两者之间的URL列表
另外,我不能投票给你的答案,因为我的声誉低于15分,除非我再获得4分。通过构建自己的
HTTPRedirectHandler
,这是一项简单的任务:
import urllib.request
class MyHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
print("newurl", headers["location"])
return super().http_error_302(req, fp, code, msg, headers)
opener = urllib.request.build_opener(MyHTTPRedirectHandler)
urllib.request.install_opener(opener)
response = urllib.request.urlopen('https://httpbin.org/redirect/6')
response.read()
同意乔治克斯的观点,
但您也可以修改以下较短的HTTPRedirectHandler
:
class MyHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
pass
类MyHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
通过
只使用
urllib
真的很重要吗?请求
包可以很容易地完成这项工作(以及许多其他工作)。使用标准库(如socket或urllib)非常重要