urllib3
是一个功能强大,条理清晰,用于HTTP客户端的Python库。
urllib3
提供了很多python标准库urllib
里所没有的重要特性:
- 线程安全
- 连接池
- 客户端SSL/TLS验证
- 文件分部编码上传
- 协助处理重复请求和HTTP重定位
- 支持压缩编码
- 支持HTTP和SOCKS代理
get请求
urllib3
主要使用连接池进行网络请求的访问,所以访问之前我们需要创建一个连接池对象,如下所示:
import urllib3
#一个PoolManager实例来生成请求,由该实例对象处理与线程池的链接以及线程安全的所有细节
http=urllib3.PoolManager()
#通过request()方法创造一个请求:
r=http.request("GET","http://www.baidu.com")
#获得登录状态码
print(r.status)
#获得html源码,utf-8解码
print(r.data.decode())
>>> import urllib3
>>> http = urllib3.PoolManager()
>>> r = http.request('GET', 'http://httpbin.org/robots.txt')
>>> r.status
200
>>> r.data
'User-agent: *\nDisallow: /deny\n'
源码:
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())
设置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())
"""
Behaves just like :class:`PoolManager`, but sends all requests through
the defined proxy, using the CONNECT method for HTTPS URLs.
:param proxy_url:
The URL of the proxy to be used.
:param proxy_headers:
A dictionary containing headers that will be sent to the proxy. In case
of HTTP they are being sent with each request, while in the
HTTPS/CONNECT case they are sent only once. Could be used for proxy
authentication.
Example:
>>> proxy = urllib3.ProxyManager('http://localhost:3128/')
>>> r1 = proxy.request('GET', 'http://google.com/')
>>> r2 = proxy.request('GET', 'http://httpbin.org/')
>>> len(proxy.pools)
1
>>> r3 = proxy.request('GET', 'https://httpbin.org/')
>>> r4 = proxy.request('GET', 'https://twitter.com/')
>>> len(proxy.pools)
3
"""
使用Timeout
#使用timeout,可以控制请求的运行时间。在一些简单的应用中,可以将timeout参数设置为一个浮点数:
r = http.request('POST',
'http://httpbin.org/post',timeout=3.0)
print(r.data.decode('utf-8'))
#让所有的request都遵循一个timeout,可以将timeout参数定义在PoolManager中:
http = urllib3.PoolManager(timeout=3.0)
# 1全域性設定超時
# http = urllib3.PoolManager(timeout = 3)
# 2在request裡設定
# http.request('post','http://httpbin.org/post',timeout = 3)
对重试和重定向进行控制
#通过设置retries参数对重试进行控制。Urllib3默认进行3次请求重试,并进行3次方向改变。
r = http.request('GET',
'http://httpbin.org/ip',retries=5)#请求重试的次数为5
print(r.data.decode('utf-8'))
##关闭请求重试(retrying request)及重定向(redirect)只要将retries定义为False即可:
r = http.request('GET',
'http://httpbin.org/redirect/1',retries=False,redirect=False)
print('d1',r.data.decode('utf-8'))
#关闭重定向(redirect)但保持重试(retrying request),将redirect参数定义为False即可
r = http.request('GET',
'http://httpbin.org/redirect/1',redirect=False)