Python__模块(网络-HTTP进阶版)__urllib3

简介

urllib3是一个三方库,用于HTTP解析或操作

提供了连接池、客户端SSL/TLS验证、文件编码上传、HTTP重定向、gzip和deflate压缩编码、HTTP和SOCKS代理等功能。

requests依赖于urllib3,做了一些封装。


文档查询

https://urllib3.readthedocs.io/en/stable/

​​​​​https://urllib3.readthedocs.io/en/stable/reference/index.html


参数列表

urllib.requests

请求模块

urllib.error

异常处理模块

urllib.parse

URL解析模块

PoolManager实例来生成请求
retries进行重试请求次数
field

导入文件信息

【例子】

filed={'filefield':('test.txt',file_data=#file.read()#)}

timeout请求超时(单位/秒)

参考代码

简单的请求

import urllib3
http=urllib3.PoolManager()
r=http.request('GET','http://www.baidu.com',retries=10)
''' 网页状态码 '''
print(r.status)
''' 解码后输出内容 '''
# print(r.data.decode('utf-8'))
''' 网页头部信息 '''
print(r.headers)

JSON传递参数

import urllib3
import json
http=urllib3.PoolManager()
data={'attribute':'value'}
''' 传递 '''
encoded_data=json.dumps(data).encode('utf-8')
r=http.request(
    'POST',
    'http://httpbin.org/post',
    body=encoded_data,
    headers={'Content-Type':'application/json'}
)
''' 接收 '''
'''
json_data=json.loads(r.data.decode('utf-8'))
'''

文件上传

import urllib3
import json
http=urllib3.PoolManager()
with open('test.txt') as fp:
    file_data=fp.read()
    rr=http.request(
        'POST',
        'http://httpbin.org/post',
        fields={
            'files':('test.txt',file_data,'text/plain'),
        }
    )
    json.loads(r.data.decode('utf-8'))['files']

自定义池

import urllib3

# 向许多不同的主机发出请求,则增加此数量可能会提高性能,同时增加内存和套接字消耗
# http = urllib3.PoolManager(num_pools=50)

''' 最大连接数:同时向同一主机发出许多请求,则增加此数量可能会提高性能 '''
http = urllib3.PoolManager(maxsize=10)
http = urllib3.HTTPConnectionPool('https://cn.bing.com', maxsize=10)


stream 和 I/O 

import urllib3
http = urllib3.PoolManager()
r = http.request(
    'GET',
    'https://httpbin.org/bytes/1024',
    preload_content=False)  
    # 预加载连接为False,即将http连接释放回连接池,以便重新使用
for chunk in r.stream(32): # stream()允许迭代响应内容的块
    print(chunk)

限制输出

import urllib3
http = urllib3.PoolManager()
response = http.request(
    'GET',
    'https://httpbin.org/bytes/1024',
    preload_content=False)
''' 调用read()将阻塞,直到有更多响应数据可用 '''
print(response.read(4)) # b'\xae\x95\n\xc2'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vip飞梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值