Python urllib3软件包的使用说明


Posted in Python onNovember 18, 2020

urllib3是一款Python 3的HTTP客户端。

Python标准库提供了urllib。在Python 2中,另外提供了urllib2;而在Python 3中,重构了urllib和urllib2到标准库urllib,并另外提供了urllib3。

1. urllib3的特性

线程安全

连接缓冲池

客户端SSL/TLS验证

文件上传

请求重试

HTTP重定向

支持gzip和deflate encoding

支持HTTP和SOCKS的代理

2. 安装

urllib3不是Python 3的标准库,要使用需要另外安装,pip命令如下:

pip install urllib3

3. 用法

1) HTTP GET请求

>>> import urllib3
>>> http = urllib3.PoolManager()
>>> r = http.request('GET', 'http://httpbin.org/robots.txt')
>>> r.status
200
>>> r.data
...
>>> r.headers
...

注意:任何HTTP请求,只有通过PoolManager对象发出,才能够提供连接缓冲池和线程安全特性。

任何请求的返回对象都是HTTPResponse对象,其中包含status, data和headers三个属性。

2) HTTP POST请求

>>> import urllib3
>>> http = urllib3.PoolManager()
>>> r = http.request('POST', 'http://httpbin.org/post', fields={'hello': 'Xiangbin'})
>>> r.status
200
>>> r.data
...
>>> r.headers
...

3) JSON响应的处理

>>> import urllib3
>>> import json
 
>>> http = urllib3.PoolManager()
>>> r = http.request('GET', 'http://httpbin.org/ip')
>>> r.data
b'{\n "origin": "10.23.1.37"\n}\n'
>>> json.loads(r.data.decode('utf-8'))
{'origin': '127.0.0.1'}

注意:使用json的loads()方法

4) 流式响应的处理

>>> import urllib3
>>> http = urllib3.PoolManager()
>>> r = http.request('GET', 'http://httpbin.org/bytes/1024', preload_content=False)
>>> for chunk in r.stream(32):
...   print(chunk)
...
>>> r.release_conn()

注意:preload_content=False表示流式处理响应数据。

处理stream()方法读取响应数据之外,还可以使用read()方法,示例如下:

>>> import urllib3
>>> http = urllib3.PoolManager()
>>> r = http.request('GET', 'http://httpbin.org/bytes/1024', preload_content=False)
>>> r.read(4)
b'\x88\x1f\x8b\xe5' 
>>> r.release_conn()

5) 请求带参数

>>> r = http.request('GET', 'http://httpbin.org/headers', fields={'hello': 'Xiangbin'}, headers={'X-Something': 'value'})

对于POST和PUT方法,需要将参数编码后,这样才可以追加到URL,示例如下:

>>> from urllib.parse import urlencode
>>> encoded_args = urlencode({'arg': 'value'})
>>> url = 'http://httpbin.org/post?' + encoded_args
>>> r = http.request('POST', url)

当然,最好还是以fields参数形式,urllib3将自动编码,示例如下:

>>> r = http.request('POST', 'http://httpbin.org/post', fields={'hello': 'Xiangbin'})

使用JSON模块,还可以以body形式发送请求参数,示例如下:

>>> import json
>>> data = {'Hello': 'Xiangbin'}
>>> 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.loads(r.data.decode('utf-8'))['json']
{'Hello': 'Xiangbin'}

6) 上传文件

文本文件

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

注意:上传文件必须使用POST方法。

二进制文件

>>> with open('example.jpg', 'rb') as fp:
...   binary_data = fp.read()
>>> r = http.request(
...   'POST',
...   'http://httpbin.org/post',
...   body=binary_data,
...   headers={'Content-Type': 'image/jpeg'})
>>> json.loads(r.data.decode('utf-8'))['data']
b'...'

补充知识:Python的requests软件包详解

requests是一款Python的第三方HTTP类库,便于进行HTTP访问。

1. requests的特性

能够发送HTTP 1.1请求

无需手工为GET方法设置URL的请求参数,无需手工为POST方法组编码表单形式

借助于urllib3实现HTTP请求的连接会话缓存

支持Python 2.6, 2.7, 3.3-3.7

2. requests的安装

requests不是Python标准库,需要使用PIP安装,命令如下:

pip install requests

安装过程如下:

C:\Sam\works>pip install requests
Collecting requests
 Downloading https://files.pythonhosted.org/packages/51/bd/23c926cd341ea6b7dd0b2a00aba99ae0f828be89d72b2190f27c11d4b7fb/requests-2.22.0-py2.py3-none-any.whl (57kB)
  100% |????????????????????????????????| 61kB 17kB/s
Collecting certifi>=2017.4.17 (from requests)
 Downloading https://files.pythonhosted.org/packages/18/b0/8146a4f8dd402f60744fa380bc73ca47303cccf8b9190fd16a827281eac2/certifi-2019.9.11-py2.py3-none-any.whl (154kB)
  100% |????????????????????????????????| 163kB 18kB/s
Collecting idna<2.9,>=2.5 (from requests)
 Downloading https://files.pythonhosted.org/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.whl (58kB)
  100% |????????????????????????????????| 61kB 10kB/s
Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 (from requests)
 Downloading https://files.pythonhosted.org/packages/e0/da/55f51ea951e1b7c63a579c09dd7db825bb730ec1fe9c0180fc77bfb31448/urllib3-1.25.6-py2.py3-none-any.whl (125kB)
  100% |????????????????????????????????| 133kB 32kB/s
Collecting chardet<3.1.0,>=3.0.2 (from requests)
 Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB)
  100% |????????????????????????????????| 143kB 48kB/s
Installing collected packages: certifi, idna, urllib3, chardet, requests
Successfully installed certifi-2019.9.11 chardet-3.0.4 idna-2.8 requests-2.22.0 urllib3-1.25.6
You are using pip version 19.0.3, however version 19.3.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

3. requests的接口

1) Main interfaces

requests.request()
requests.head()
requests.get('url', params={'key1':'value1', 'key2':'value2'},headers={'user-agent': '...'}, cookies={'name1':'value2'})
requests.post('url', data={'key':'value'})
requests.post('url', json={'key':'value'})
requests.post('url', files={'uploaded_file': open('report.xls', 'rb')})
requests.post('url', files={'uploaded_file': ('report.xls', open('report.xls', 'rb'), 'application/excel', {'Expires': '0'})})
requests.post('url', files={'uploaded_file': ('temp.txt', 'one line\ntwo lines\n')})
requests.put('url', data={'key':'value'})
requests.patch()
requests.delete('url')
def getGithub():
  github_url = 'https://api.github.com/user/repos'
  myresponse = requests.get(github_url, auth=('champagne', 'myPassword'))
  print(myresponse.json())
def postGithub():
  github_url = 'https://api.github.com/user/repos'
  data = json.dumps({'name':'python test', 'description':'a python test repo'})
  myresponse = requests.post(github_url, data, auth=('champagne', 'myPassword'))
  print(myresponse.text)

2) requests.Session类

import requests

requests.Session()

3) requests.Request类

import requests

requests.Request('GET', 'http://httpbin.org/get')

4) requests.PreparedRequest类

import requests
req = requests.Request('GET', 'http://httpbin.org/get')
preq = req.prepare()

5) requests.Response类

import requests
r = requests.get('https://api.github.com/events')
r.headers['content-type'] #'application/json;charset=utf8'
r.url
r.status_code #200==requests.codes.ok
r.encoding #'utf-8' by default
r.raw #raw content
r.text #text content
r.content #binary content
r.json()#json content, recommended
r.cookies['a_key']

注意:调用json()方法,如果返回结果不是有效的JSON数据,则抛出ValueError异常。

6) requests.adapters.BaseAdapter类

7) requests.adapters.HTTPAdapter类

requests提供的使用urllib3的HTTP Adapter

以上这篇Python urllib3软件包的使用说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中Collection的使用小技巧
Aug 18 Python
python使用reportlab实现图片转换成pdf的方法
May 22 Python
详解python如何调用C/C++底层库与互相传值
Aug 10 Python
从CentOS安装完成到生成词云python的实例
Dec 01 Python
python中实现字符串翻转的方法
Jul 11 Python
python 读取文件并替换字段的实例
Jul 12 Python
对python使用telnet实现弱密码登录的方法详解
Jan 26 Python
itchat-python搭建微信机器人(附示例)
Jun 11 Python
python 利用turtle库绘制笑脸和哭脸的例子
Nov 23 Python
python生成任意频率正弦波方式
Feb 25 Python
Python selenium 加载并保存QQ群成员,去除其群主、管理员信息的示例代码
May 28 Python
Python实战之实现康威生命游戏
Apr 26 Python
Python从文件中读取数据的方法步骤
Nov 18 #Python
详解Python中如何将数据存储为json格式的文件
Nov 18 #Python
python3中calendar返回某一时间点实例讲解
Nov 18 #Python
关于Python3的import问题(pycharm可以运行命令行import错误)
Nov 18 #Python
python 实现弹球游戏的示例代码
Nov 17 #Python
最新PyCharm从安装到PyCharm永久激活再到PyCharm官方中文汉化详细教程
Nov 17 #Python
python 发送get请求接口详解
Nov 17 #Python
You might like
基于PHP中的常用函数回顾
2013/07/11 PHP
php获取URL中带#号等特殊符号参数的解决方法
2014/09/02 PHP
PHP实现的最大正向匹配算法示例
2017/12/19 PHP
最近项目写了一些js,水平有待提高
2009/01/31 Javascript
基于jquery的监控数据是否发生改变
2011/04/11 Javascript
查找Oracle高消耗语句的方法
2014/03/22 Javascript
jQuery函数的第二个参数获取指定上下文中的DOM元素
2014/05/19 Javascript
JS应用正则表达式转换大小写示例
2014/09/18 Javascript
使用命令对象代替switch语句的写法示例
2015/02/28 Javascript
基于jQuery实现表格的查看修改删除
2016/08/01 Javascript
JS文件/图片从电脑里面拖拽到浏览器上传文件/图片
2017/03/08 Javascript
Angular在模板驱动表单中自定义校验器的方法
2017/08/09 Javascript
微信小程序滚动Tab实现左右可滑动切换
2017/08/17 Javascript
原生JS+HTML5实现跟随鼠标一起流动的粒子动画效果
2018/05/03 Javascript
微信小程序常用简易小函数总结
2019/02/01 Javascript
axios封装,使用拦截器统一处理接口,超详细的教程(推荐)
2019/05/02 Javascript
JS数组方法concat()用法实例分析
2020/01/18 Javascript
JS数组索引检测中的数据类型问题详解
2021/01/11 Javascript
python中yaml配置文件模块的使用详解
2018/04/27 Python
Django中使用Whoosh进行全文检索的方法
2019/03/31 Python
使用python批量修改文件名的方法(视频合并时)
2020/03/24 Python
Python SQLAlchemy入门教程(基本用法)
2019/11/11 Python
在python里使用await关键字来等另外一个协程的实例
2020/05/04 Python
Python网页解析器使用实例详解
2020/05/30 Python
为2021年的第一场雪锦上添花:用matplotlib绘制雪花和雪景
2021/01/05 Python
纯CSS3制作的简洁蓝白风格的登录模板(非IE效果更好)
2013/08/11 HTML / CSS
阿玛尼美妆加拿大官方商城:Giorgio Armani Beauty加拿大
2017/10/24 全球购物
店长岗位的工作内容
2013/11/12 职场文书
城市精细化管理实施方案
2014/03/04 职场文书
物流管理专业自荐信
2014/06/23 职场文书
军人离婚协议书样本
2014/10/21 职场文书
幼儿园教师节感谢信
2015/01/23 职场文书
贪污检举信范文
2015/03/02 职场文书
2016开学第一课心得体会
2016/01/23 职场文书
MySQL 隔离数据列和前缀索引的使用总结
2021/05/14 MySQL
Android 中的类文件和类加载器详情
2022/06/05 Java/Android