PythonHandler处理器和自定义Opener原理详解-创新互联
我们之前一直都在使用的urlopen,这是一个特殊的opener(也就是模块帮我们构建好的)。
但是基本的urlopen()方法不支持代理、cookie等其他的HTTP/HTTPS高级功能。所以要支持这些功能:
1.使用相差的Handler处理器来创建特定功能的处理器对象;
2.然后通过urllib.request.build_opener()方法,创建自定义opener对象
3.使用自定义的opener对象,调用open()方法发送请求。
如果程序里所有的请求都使用自定义的opener,可以使用urllib.request.install_opener()将自定义的opener对象定义为全局opener,表示如果之后凡是调用urlopen,都将使用这个opener(根据自己的需求来选择)
简单的自定义opener()
#!/usr/bin/python3 # -*- coding:utf-8 -*- __author__ = 'mayi' import urllib.request # 构建一个HTTPHandler处理器对象,支持处理HTTP请求。 http_handler = urllib.request.HTTPHandler() # # 构建一个HTTPSHandler处理器对象,支持处理HTTPS请求 # https_handler = urllib.request.HTTPSHandler() # 调用urllib.request.build_opener()方法,创建支持处理HTTP请求的opener对象 opener = urllib.request.build_opener(http_handler) # 构建Request请求 request = urllib.request.Request("http://www.baidu.com/") # 调用自定义opener对象的open()方法,发送request请求 response = opener.open(request) # 获取服务器响应内容 html = response.read() print(html)
分享文章:PythonHandler处理器和自定义Opener原理详解-创新互联
标题网址:http://myzitong.com/article/dsoogi.html