我想学习“将urllib.BaseHandler子类化”,但是它行不通! 它仍然受模块默认设置的影响,该默认设置返回如下:“ Python-urllib / 3.7”
代码是:
import urllib.request as request
class HeaderHandler(request.BaseHandler):
handler_order = 900
def __init__(self,headers=None):
if headers is None:
headers = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0'
self.headers = headers
def http_request(self,req):
req.add_header('User-Agent',self.headers)
return req
https_request = http_request
url = 'http://httpbin.org/get'
headerhandler = HeaderHandler()
handlers = [headerhandler,]
opener = request.build_opener(*handlers)
req = request.Request(url)
response = opener.open(req)
print(response.read().decode('utf-8'))
不要告诉我写这样的代码:
import requests
requests.get(url,headers=headers)
or
import urllib.request as urlreq
req = urlreq.Request(url,headers={...})
urlopen(req)
因为我只想知道为什么不能使用该方式以及如何对其进行修改