Python3 Requests第三方网络请求库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Rozol/article/details/79960568

Python3 Requests第三方网络请求库


本文由 Luzhuo 编写,转发请保留该信息.
原文: https://blog.csdn.net/Rozol/article/details/79960568


以下代码以Python3.6.1为例
Less is more!

#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2018/4/16'

'''
    第三方网络库, 比Python自带的request使用更简洁方便
    无需手动为URL添加查询字典, 无需对POST数据进行表单编码, Keep-alive和HTTP连接池的功能100%自动化
    [Requests的中文文档](http://docs.python-requests.org/zh_CN/latest/index.html)
    [Requests的Github地址](https://github.com/requests/requests)
    requests-2.18.4
    pip install requests
'''

import requests
from PIL import Image  # 需要安装PIL库
from io import BytesIO
import json


url = 'http://www.baidu.com'
def funcs():

    # --- 请求 ---
    # GET请求
    res = requests.get(url)
    # POST请求
    res = requests.post(url, data={'key': 'value'})
    # 其他请求
    res = requests.put(url, data={'key': 'value'})
    res = requests.delete(url)
    res = requests.head(url)
    res = requests.options(url)



    # --- 传递参数 ---
    payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
    res = requests.get(url, params=payload)



    # --- 传递数据 ---
    # Get 请求头
    headers = {'User - Agent': 'Mozilla / 5.0...'}
    res = requests.get(url, headers=headers)

    # Post
    payload = {'key1': 'value1', 'key2': 'value2'}  # 字典
    payload = (('key1', 'value1'), ('key1', 'value2'))  # 元组
    res = requests.post(url, data=payload)  # 表单
    res = requests.post(url, data=json.dumps(payload))  # json
    res = requests.post(url, json=payload)  # json
    files = {'file': open('abc.txt', 'rb')}
    files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
    res = requests.post(url, files=files)  # 文件

    # SSL证书
    requests.get('https://www.douyu.com', verify=False)  # verify=False  取消证书验证
    requests.get(url, verify='/path/to/certfile')  # 指定证书, 传入CA证书文件或文件夹路径(文件夹路径需要经过 OpenSSL 提供的 c_rehash 工具处理)
    requests.get(url, cert=('/path/client.cert', '/path/client.key'))  # 客户端证书




    # --- 获取数据 ---
    # 获取url(最终)
    url_str = res.url
    # 获取状态码
    code_int = res.status_code
    # 请求头
    headers_list = res.request.headers
    # 响应头 (不区分大小写)
    headers_list = res.headers
    header_str = res.headers['Content-Type']
    header_str = res.headers.get('content-type')

    # 编码格式
    encoding_str = res.encoding
    res.encoding = 'UTF-8'  # 修改编码即生效 (自动解码编码不准, 可能是bug, 最好指定编码格式)
    # 响应内容 (Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据)
    data_str = res.text  # (Requests 会基于 HTTP 头部对响应的编码和charade来做出解码[不准])
    # 响应内容(用字节方式访问, 适用于非文本请求)
    data = res.content
    # 创建图片(从二进制数据)
    image = Image.open(BytesIO(data))
    # 获取json内容 (没有json内容将抛异常)
    json_str = res.json()


    # --- cookie ---
    # -- 手动设置 --
    # 获取cookie
    cookies_list = res.headers['Set-Cookie']  # 响应的cookie
    cookie_str = res.cookies['BDORZ']  # 获取指定的cookie
    cookiedict = requests.utils.dict_from_cookiejar(res.cookies)  # 将cookie转成字典格式
    cookies = dict(BDORZ='27315')
    # 设置cookie
    res = requests.get(url, cookies=cookies)
    jar = requests.cookies.RequestsCookieJar()  # 适合跨域名跨路径使用的cookie管理器(不会自动帮你设置cookie)
    jar.set('key1', 'value1', domain='域名', path='路径')
    jar.set('key2', 'value2', domain='www.baidu.com', path='/abc')  # 'http://www.baidu.com/abc'
    res = requests.get(url, cookies=jar)

    # -- 自动设置 --
    # 会话对象让你能够跨请求保持某些参数(如:Cookie), 并且会重用连接, 效率高
    s = requests.Session()
    res = s.get(url)


    # --- Session ---
    # 参数设置
    s = requests.Session()  # 可使用with管理: with requests.Session() as s:
    s.auth = ('user', 'pass')  # 认证账号密码
    s.headers.update({'key1': 'value1'})  # 更新头
    s.cookies = 'xxx'  # 手动添加cookie
    s.verify = '/path/to/certfile'  # 设置CA证书
    s.cert = '/path/client.cert'  # 设置客户端证书
    s.get('http://httpbin.org/headers', headers={'key2': 'value2'})  # 方法层设置的头信息, 与会话层设置的头信息合并, 方法层会覆盖会话层参数; 另外方法层的参数不会被跨站保持



    # --- 代理 ---
    proxies = {
        "http": "http://10.10.1.10:3128",
        "https": "http://10.10.1.10:1080",
        "http": "http://user:[email protected]:3128/",  # 需要验证的代理
        'http://10.20.1.128': 'http://10.10.1.10:5323',  # 为指定的主机设置代理
        'http': 'socks5://user:pass@host:port',  # 为Socket设置代理 (需要安装第三方库 pip install requests[socks])
    }
    requests.get("http://example.org", proxies=proxies)



    # --- 请求重定向(Requests 会自动处理所有重定向(除HEAD, 需要手动启动)) ---
    res = requests.get('http://luzhuo.me')  # allow_redirects=False 可禁止重定向
    print(res.url)  # 获取最终的url
    # history 是 Response 对象的列表, 为了完成请求而创建, 按照从旧到新的顺序排序
    historys_list = res.history



    # --- 响应超时 ---
    # 如果不指定, requests会一直等待连接(可能是几分钟, 有可能更长)
    requests.get(url, timeout=3)  # 连接时间
    requests.get('https://github.com', timeout=(3.05, 27))  # (连接时间. 读取时间)
    requests.get('https://github.com', timeout=None)  # 永久等待




    # --- 异常 ---
    ConnectionError  # 网络异常
    Timeout  # 请求超时
    TooManyRedirects  # 超过最大重定向次数
    requests.exceptions.RequestException  # 所有异常均继承于此



    # --- 其他 ---
    # 延迟下载响应体
    with requests.get(url, stream=True) as r:  # stream=True 响应体不会被下载, 只下载响应头, 直到访问 .content 才下载(我们可通过响应头来决定是否要下载响应体)
        r.content  # 只有数据被全部获取, 连接才会被放入连接池
    # 流式上传
    with open('body.file', 'rb') as f:  # 数据不会被加载到内存, 直接读取上传
        requests.post(url, data=f)
    # 身份验证
    # 基本身份验证
    from requests.auth import HTTPBasicAuth
    requests.get(url, auth=('user', 'pass'))
    requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
    # 摘要式身份认证
    from requests.auth import HTTPDigestAuth
    requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
    # OAuth 1 认证
    from requests_oauthlib import OAuth1  # 需要安装 requests_oauthlib
    requests.get(url, auth=OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET', 'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET'))



# 使用演示
def demo():
    with requests.Session() as s:
        res = s.get(url)
        res.encoding = 'utf-8'
        print(res.encoding)
        print(res.text)



if __name__ == "__main__":
    demo()
    funcs()

猜你喜欢

转载自blog.csdn.net/Rozol/article/details/79960568
今日推荐