Python爬虫:请求标准库 urllib3

urllib3是一个功能强大,条理清晰,用于HTTP客户端的Python库。
urllib3提供了很多python标准库urllib里所没有的重要特性:

  1. 线程安全
  2. 连接池
  3. 客户端SSL/TLS验证
  4. 文件分部编码上传
  5. 协助处理重复请求和HTTP重定位
  6. 支持压缩编码
  7. 支持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 必选,指定是什么请求
    getGETPOSTpostPUTDELETE等,不区分大小写。
  • 第二个参数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)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值