urllib库request模块中各种Handler的用法总结如下:
# !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
HTTPHandler
HTTPBasicAuthHandler
ProxyHandler
ProxyBasicAuthHandler
HTTPCookieProcessor
"""
import urllib.request
import urllib.parse
import http.cookiejar
# HTTPHandler,普通的HTPP处理器,等价于直接用urlopen()方法
url="http://www.baidu.com/"
# 获取handler
# 可以传递参数 debuglevel=1 ,打开调试模式
http_handler=urllib.request.HTTPHandler()
# 获取opener,参数为处理器对象,可以传递多个
opener=urllib.request.build_opener(http_handler)
# 方式一:安装全局的代理处理器
urllib.request.install_opener(opener)
resp=urllib.request.urlopen(url)
# 方式二:代理处理器只在当前代码块生效
# resp=opener.open(),接收一个url或Request对象,返回Response
# 接收url
# resp=opener.open(url)
# 接收Request对象
# req=urllib.request.Request(url,data=b'form data',headers={})
# resp=opener.open(req)
print(resp.read().decode('utf-8'))
# HTTPBasicAuthHandler,需要进行验证的HTTP处理器
# HTTPPasswordMgrWithDefaultRealm,密码信息管理器
http_passwd_mgr=urllib.request.HTTPPasswordMgrWithDefaultRealm()
http_passwd_mgr.add_password(realm=None,uri="test.com",user="username",passwd="password")
# 创建验证处理器对象,参数为密码管理器
http_auth_handler=urllib.request.HTTPBasicAuthHandler(http_passwd_mgr)
# 构造opener
opener=urllib.request.build_opener(http_auth_handler)
# open
resp=opener.open("fullurl")
print(resp.status)
# 代理处理器
proxy_switch=True
url="http://www.baidu.com/"
# ProxyHandler
# 开放代理
# 创建代理处理器,参数为字典{"代理类型":"代理地址"}
null_proxy_handler=urllib.request.ProxyHandler({})
public_proxy_handler=urllib.request.ProxyHandler({"https":"14.221.165.43:9797"})
# 私有代理(需要进行验证)
# 方式一:
proxy_auth_handler=urllib.request.ProxyHandler({"https":"username:passwd@14.221.165.43:9797"})
# 方式二:
# ProxyBasicAuthHandler(与HTTPBasicAuthHandler相同)
# 根据需求,构建opener
if proxy_switch:
opener=urllib.request.build_opener(public_proxy_handler,proxy_auth_handler)
else:
opener=urllib.request.build_opener(null_proxy_handler,proxy_auth_handler)
resp=opener.open(url)
print(resp.read().decode('utf-8'))
"""
处理Cookie
cookie处理器
urllib.request.HTTPCookieProcessor
# 保存cookie信息
http.cookiejar.CookieJar
http.cookiejar.FileCookieJar
http.cookiejar.MozillaCookieJar
http.cookiejar.LWPCookieJar
"""
url="http://test.com/"
form_data={"username":"username","password":"password",}
form_data=urllib.parse.urlencode(form_data).encode('utf-8')
request_headers={}
req=urllib.request.Request(url,data=form_data,headers=request_headers)
# 获取CookieJar对象
cookiejar=http.cookiejar.CookieJar()
# 获取cookie处理器对象
# 参数为CookieJar对象,将自动把第一次POST请求时,生成的cookie信息保存起来,
# 以后再请求同一服务器时,将自动提供该信息
cookie_handler=urllib.request.HTTPCookieProcessor(cookiejar)
# 构建opener
opener=urllib.request.build_opener(cookie_handler)
resp=opener.open(req)
print(resp.getcode())
# 再次访问已登录的网站,此时,将自动使用cookie信息。
resp=opener.open("test_url")