python爬虫之urllib3的使用示例

yipeiwu_com7年前Python爬虫

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
  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实现的一只从百度开始不断搜索的小爬虫

文中用到了BeautifulSoup这个库, 目的是处理html文档分析的, 因为我只是提取了title的关键字,所以可以用正则表达式代替, 还有一个库是jieba, 这个库是中文分词的作用, 再有一...

python3.4爬虫demo

python 3.4 所写爬虫 仅仅是个demo,以百度图片首页图片为例。能跑出图片上的图片; 使用 eclipse pydev 编写: from SpiderSimple.HtmL...

python3实现网络爬虫之BeautifulSoup使用详解

python3实现网络爬虫之BeautifulSoup使用详解

这一次我们来了解一下美味的汤--BeautifulSoup,这将是我们以后经常使用的一个库,并且非常的好用。 BeautifuleSoup库的名字取自刘易斯·卡罗尔在《爱丽丝梦游仙境》里...

python网络爬虫之如何伪装逃过反爬虫程序的方法

有的时候,我们本来写得好好的爬虫代码,之前还运行得Ok, 一下子突然报错了。 报错信息如下: Http 800 Internal internet error 这是因为你的对象网站设置了...

Python反爬虫技术之防止IP地址被封杀的讲解

Python反爬虫技术之防止IP地址被封杀的讲解

在使用爬虫爬取别的网站的数据的时候,如果爬取频次过快,或者因为一些别的原因,被对方网站识别出爬虫后,自己的IP地址就面临着被封杀的风险。一旦IP被封杀,那么爬虫就再也爬取不到数据了。 那...