Myluzh Blog

Strive to become a dream architect.

python使用urllib3库实现HTTP请求

发布时间: 2020-4-15 文章作者: myluzh 分类名称: Python


使用urllib3库生成一个完整的http请求,请求应该包含请求方式、请求连接、请求头、超时时间和重试次数。通过request方法可以创建一个请求,该方法返回http响应对象,语法如下:
urllib3.request(method,url,headers,timeout)
参数 说明
method
接收string。表示请求类型,例如GET,无默认值
url
接收string。表示请求的URL,无默认值
headers
接收dict。请求头,默认为None
data
接收dict。POST提交的数据
timeout
接收float。设置请求超时时间
fields
接收dict。表示所请求类型自带参数,默认为None
**urlopen_kw
接收dict或者其他python中类型的数据。根据具体需要可添加的参数,无默认值

实例:
import urllib3

# 发送请求实例
http = urllib3.PoolManager()

# 请求网址
url = 'http://www.xxx.com/index.html'
# 请求头
head = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'}
# 超时时间(connect连接超时时间,read读取超时时间)
tm = urllib3.Timeout(connect=1.0, read=3.0)
# retries重试次数,redirect重定向次数
rq = http.request('GET', url=url, headers=head, timeout=tm, retries=5, redirect=4)

print('服务器响应码:', rq.status)
print('响应实体', rq.data.decode('utf-8'))

标签: python urllib3

发表评论