• Requests库


    构建HTTP请求

    构建请求URL参数

    https://www.baidu.com/s?wd=iphone&rsv_spt=1
    
    • 1

    问号后面的部分 wd=iphone&rsv_spt=1 就是 url 参数,每个参数之间是用 & 隔开的。

    但是有的时候,我们的url参数里面有些特殊字符,比如 参数的值就包含了 & 这个符号。

    那么我们可以把这些参数放到一个字典里面,然后把字典对象传递给 Requests请求方法的 params 参数,如下

    urlpara = {
        'wd':'iphone&ipad',
        'rsv_spt':'1'
    }
    
    response = requests.get('https://www.baidu.com/s',params=urlpara)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    构建请求消息头

    每个消息头也就是一种 键值对的格式存放数据,如下所示

    user-agent: my-app/0.0.1
    auth-type: jwt-token
    
    • 1
    • 2
    headers = {
        'user-agent': 'my-app/0.0.1', 
        'auth-type': 'jwt-token'
    }
    r = requests.post("http://httpbin.org/post", headers=headers)
    print(r.text)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    构建请求消息体

    Web API接口中,消息体基本都是文本,文本的格式主要是这3种: urlencoded ,json , XML。

    XML 格式消息体

    如果设计者决定用 XML 格式传输一段信息,用Requests库,只需要这样

    payload = '''
    
    
        良好
        30%
        暂无
    
    '''
    
    r = requests.post("http://httpbin.org/post",
                      data=payload.encode('utf8'))
    print(r.text)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    urlencoded 格式消息体

    这种格式的消息体就是一种 键值对的格式存放数据,如下所示

    key1=value1&key2=value2
    
    • 1

    然后使用post方法的时候,指定参数 data 的值为这个字典就可以了,如下

    payload = {'key1': 'value1', 'key2': 'value2'}
    
    r = requests.post("http://httpbin.org/post", data=payload)
    print(r.text)
    
    • 1
    • 2
    • 3
    • 4

    json 格式消息体

    可以使用json库的dumps方法,如下

    import requests,json
    
    payload = {
        "Overall":"良好",
        "Progress":"30%",
        "Problems":[
            {
                "No" : 1,
                "desc": "问题1...."
            },
            {
                "No" : 2,
                "desc": "问题2...."
            },
        ]
    }
    
    r = requests.post("http://httpbin.org/post", data=json.dumps(payload))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    也可以将 数据对象 直接 传递给post方法的 json参数,如下

    r = requests.post("http://httpbin.org/post", json=payload)
    
    • 1

    检查HTTP响应

    检查响应状态码

    要检查 HTTP 响应 的状态码,直接 通过 reponse对象的 status_code 属性获取

    import requests
    
    response = requests.get('http://mirrors.sohu.com/')
    print(response.status_code)
    
    • 1
    • 2
    • 3
    • 4

    检查响应消息头

    要检查 HTTP 响应 的消息头,直接 通过 reponse对象的 headers 属性获取

    import requests,pprint
    
    response = requests.get('http://mirrors.sohu.com/')
    
    print(type(response.headers))
    
    pprint.pprint(dict(response.headers))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    运行结果如下

    <class 'requests.structures.CaseInsensitiveDict'>
    {'Cache-Control': 'no-store',
     'Connection': 'keep-alive',
     'Content-Type': 'text/html; charset=utf8',
     'Date': 'Sat, 21 Sep 2019 09:02:32 GMT',
     'Server': 'nginx',
     'Transfer-Encoding': 'chunked'}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    response.headers 对象的类型 是 继承自 Dict 字典 类型的一个 类。

    我们也可以像操作字典一样操作它,比如取出一个元素的值

    print(response.headers['Content-Type'])
    
    • 1

    检查响应消息体

    获取响应的消息体的文本内容,直接通过response对象 的 text 属性即可获取

    import requests
    
    response = requests.get('http://mirrors.sohu.com/')
    print(response.text)
    
    • 1
    • 2
    • 3
    • 4

    但是有时候,服务端并不一定会在消息头中指定编码格式,这时, requests的推测可能有误,需要我们指定编码格式。

    可以通过这样的方式指定

    import requests
    
    response = requests.get('http://mirrors.sohu.com/')
    response.encoding='utf8'
    print(response.text)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    如果我们要直接获取消息体中的字节串内容,可以使用 content 属性,

    比如

    import requests

    response = requests.get('http://mirrors.sohu.com/')
    print(response.content)
    
    • 1
    • 2

    当然,如果可以直接对 获取的字节串 bytes对象进行解码

    print(response.content.decode('utf8'))
    
    • 1

    session机制

    requests库给我们提供一个 Session 类 。通过这个类,无需我们操心, requests库自动帮我们保存服务端返回的 cookie数据, HTTP请求自动 在消息头中放入 cookie 数据。

    import requests
    
    # 打印HTTP响应消息的函数
    def printResponse(response):
        print('\n\n-------- HTTP response * begin -------')
        print(response.status_code)
    
        for k, v in response.headers.items():
            print(f'{k}: {v}')
    
        print('')
    
        print(response.content.decode('utf8'))
        print('-------- HTTP response * end -------\n\n')
    
    
    # 创建 Session 对象
    s = requests.Session()
    
    # 通过 Session 对象 发送请求
    response = s.post("http://127.0.0.1/api/mgr/signin",
           data={
               'username': 'byhy',
               'password': '88888888'
           })
    
    printResponse(response)
    
    # 通过 Session 对象 发送请求
    response = s.get("http://127.0.0.1/api/mgr/customers",
          params={
              'action'    :  'list_customer',
              'pagesize'  :  10,
              'pagenum'   :  1,
              'keywords'  :  '',
          })
    
    printResponse(response)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
  • 相关阅读:
    微信小程序的开发---tabBar的介绍
    【重拾C语言】七、指针(三)指针与字符串(字符串与字符串数组;指针与字符串的遍历、拷贝、比较;反转字符串)
    hiveSql 各时段观看直播人数
    基于JAVA SpringBoot的综合博客系统的设计与实现源码
    HFSS-API入门第二弹:基本形状和操作
    (一)Win10安装MindSpore平台
    angr原理与实践(二)—— 各类图的生成(CFG CG ACFG DDG等)
    前端小案例-图片存放在远端服务器
    修复vite中使用react提示Fast refresh only works when a file only exports components.
    机器学习与数据挖掘第三、四周
  • 原文地址:https://blog.csdn.net/qq_52563729/article/details/133208101