python爬虫之urllib3的使用示例


Posted in Python onJuly 09, 2018

Urllib3是一个功能强大,条理清晰,用于HTTP客户端的Python库。许多Python的原生系统已经开始使用urllib3。Urllib3提供了很多python标准库urllib里所没有的重要特性:

  1. 线程安全
  2. 连接池
  3. 客户端SSL/TLS验证
  4. 文件分部编码上传
  5. 协助处理重复请求和HTTP重定位
  6. 支持压缩编码
  7. 支持HTTP和SOCKS代理

一、get请求

urllib3主要使用连接池进行网络请求的访问,所以访问之前我们需要创建一个连接池对象,如下所示:

import urllib3

url = "http://httpbin.org"
http = urllib3.PoolManager();
r = http.request('GET',url+"/get")
print(r.data.decode())
print(r.status)

带参数的get
r = http.request('get','http://www.baidu.com/s',fields={'wd':'周杰伦'})
print(r.data.decode())

经查看源码:

def request(self, method, url, fields=None, headers=None, **urlopen_kw):
  • 第一个参数method 必选,指定是什么请求,'get'、'GET'、'POST'、'post'、'PUT'、'DELETE'等,不区分大小写。
  • 第二个参数url,必选
  • 第三个参数fields,请求的参数,可选
  • 第四个参数headers 可选

request请求的返回值是<urllib3.response.HTTPResponse object at 0x000001B3879440B8>

我们可以通过dir()查看其所有的属性和方法。

dir(r)

直截取了一部分

#'data', 'decode_content', 'enforce_content_length', 'fileno', 'flush', 'from_httplib',
# 'get_redirect_location', 'getheader', 'getheaders', 'headers', 'info', 'isatty',
# 'length_remaining', 'read', 'read_chunked', 'readable', 'readinto', 'readline',
# 'readlines', 'reason', 'release_conn', 'retries', 'seek', 'seekable', 'status',
# 'stream', 'strict', 'supports_chunked_reads', 'tell', 'truncate', 'version', 'writable',
# 'writelines']

二、post请求

import urllib3
url = "http://httpbin.org"
fields = {
  'name':'xfy'
}
http = urllib3.PoolManager()
r = http.request('post',url+"/post",fields=fields)
print(r.data.decode())

可以看到很简单,只是第一个参数get换成了post。

并且参数不需要再像urllib一样转换成byte型了。

三、设置headers

import urllib3
headers = {
   'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
}
http = urllib3.PoolManager();
r = http.request('get',url+"/get",headers = headers)
print(r.data.decode())

四、设置代理

import urllib3
url = "http://httpbin.org"
headers = {
   'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
}
proxy = urllib3.ProxyManager('http://101.236.19.165:8866',headers = headers)
r = proxy.request('get',url+"/ip")
print(r.data.decode())

五、当请求的参数为json

在发起请求时,可以通过定义body 参数并定义headers的Content-Type参数来发送一个已经过编译的JSON数据

import urllib3
url = "http://httpbin.org"
import json
data = {'name':'徐繁韵'}

json_data = json.dumps(data)

http = urllib3.PoolManager()
r = http.request('post',url+"/post",body = json_data,headers = {'Content-Type':'application/json'})
print(r.data.decode('unicode_escape'))

六、上传文件

#元组形式
with open('a.html','rb') as f:
  data = f.read()
http = urllib3.PoolManager()
r = http.request('post','http://httpbin.org/post',fields = {'filefield':('a.html',data,'text/plain')})
print(r.data.decode())

#二进制形式

r = http.request('post','http://httpbin.org/post',body = data,headers={'Content-Type':'image/jpeg'})
print(r.data.decode())

七、超时设置

# 1全局设置超时
# http = urllib3.PoolManager(timeout = 3)
# 2在request里设置
# http.request('post','http://httpbin.org/post',timeout = 3)

八、重试和重定向

import urllib3
http = urllib3.PoolManager()
#重试
r = http.request('post','http://httpbin.org/post',retries = 5) #请求重试测次数为5次 ,默认为3ci
print(r.retries) #Retry(total=5, connect=None, read=None, redirect=0, status=None)
#关闭重试
http.request('post','http://httpbin.org/post',retries = False) #请求重试测次数为5次 ,默认为3ci

r = http.request('get','http://httpbin.org/redirect/1',redirect = False)
print(r.retries)# Retry(total=3, connect=None, read=None, redirect=None, status=None)
print(r.status)
print(r.data.decode())
print("--------------------")
print(r.get_redirect_location())
#302不是异常

九、urllib3 本身设置了https的处理,但是有警告

虽然可以请求,但是报如下警告:

InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)

禁用警告:

import urllib3
urllib3.disable_warnings() #禁用各种警告
url = "https://www.12306.cn/mormhweb/"
http = urllib3.PoolManager()
r = http.request('get',url)
print(r.data.decode())

urllib3很强大,但是并没有requests好用。了解为主。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python创建文件和追加文件内容实例
Oct 21 Python
Python编程中使用Pillow来处理图像的基础教程
Nov 20 Python
全面了解Python环境配置及项目建立
Jun 30 Python
python list排序的两种方法及实例讲解
Mar 20 Python
Python语言的变量认识及操作方法
Feb 11 Python
Python迭代器与生成器用法实例分析
Jul 09 Python
python版本五子棋的实现代码
Dec 11 Python
对dataframe数据之间求补集的实例详解
Jan 30 Python
python实现学员管理系统
Feb 26 Python
详解Python 爬取13个旅游城市,告诉你五一大家最爱去哪玩?
May 07 Python
python mongo 向数据中的数组类型新增数据操作
Dec 05 Python
这样写python注释让代码更加的优雅
Jun 02 Python
机器学习之KNN算法原理及Python实现方法详解
Jul 09 #Python
Python实现基于KNN算法的笔迹识别功能详解
Jul 09 #Python
Python 16进制与中文相互转换的实现方法
Jul 09 #Python
python 文件转成16进制数组的实例
Jul 09 #Python
使用Python读取二进制文件的实例讲解
Jul 09 #Python
Python实现随机漫步功能
Jul 09 #Python
Python2包含中文报错的解决方法
Jul 09 #Python
You might like
浅析php工厂模式
2014/11/25 PHP
php简单判断两个字符串是否相等的方法
2015/07/13 PHP
php封装的page分页类完整实例
2016/10/18 PHP
深入浅析安装PhpStorm并激活的步骤详解
2020/09/17 PHP
javascript OFFICE控件测试代码
2009/12/08 Javascript
使用jQuery避免鼠标双击的解决方案
2013/08/21 Javascript
超链接的禁用属性Disabled使用示例
2014/07/31 Javascript
JQuery给网页更换皮肤的方法
2015/05/30 Javascript
Javascript控制div属性动态变化实例分析
2015/10/08 Javascript
JS+CSS实现的经典圆角下拉菜单效果代码
2015/10/21 Javascript
jquery hover 不停闪动问题的解决方法(亦为stop()的使用)
2017/02/10 Javascript
Angular2入门--架构总览
2017/03/29 Javascript
vue-cli 打包后提交到线上出现 &quot;Uncaught SyntaxError:Unexpected token&quot; 报错
2018/11/06 Javascript
jQuery zTree插件快速实现目录树
2019/08/16 jQuery
[08:17]Ti9 现场cosplay
2019/09/10 DOTA
Python argv用法详解
2016/01/08 Python
深入讲解Java编程中类的生命周期
2016/02/05 Python
Python生成密码库功能示例
2017/05/23 Python
python3 模拟登录v2ex实例讲解
2017/07/13 Python
详解TensorFlow查看ckpt中变量的几种方法
2018/06/19 Python
解决Python3 控制台输出InsecureRequestWarning问题
2019/07/15 Python
对Keras中predict()方法和predict_classes()方法的区别说明
2020/06/09 Python
Opencv 图片的OCR识别的实战示例
2021/03/02 Python
Python3自带工具2to3.py 转换 Python2.x 代码到Python3的操作
2021/03/03 Python
纯css实现照片墙3D效果的示例代码
2017/11/13 HTML / CSS
Tech21美国/加拿大:英国NO.1防摔保护壳品牌
2018/01/20 全球购物
十月份红领巾广播稿
2014/01/22 职场文书
主管会计岗位责任制
2014/02/10 职场文书
《红军不怕远征难》教学反思
2014/04/14 职场文书
雷锋精神演讲稿
2014/05/13 职场文书
宿舍标语大全
2014/06/19 职场文书
五年级学生期末评语
2014/12/26 职场文书
创业计划书之烤红薯
2019/09/26 职场文书
深度学习小工程练习之垃圾分类详解
2021/04/14 Python
MySQL COUNT函数的使用与优化
2021/05/10 MySQL
pandas进行数据输入和输出的方法详解
2022/03/23 Python