• python之requests库


    介绍

    requests是python用于处理http/https的一个第三方库,需要pip安装。

    request函数

    import requests
    res = requests.request(method='GET', url='https://www.baidu.com/');
    
    • requests是一个函数,method和url参数必须给定
    • res的类型为<class 'requests.models.Response'>

    (1)method

    • 该参数必须设置,一般是GET、POST、PUT、DELETE、PATCH、OPTIONS、HEAD。也可以是小写,或者混杂

    • method设置错误,比如为GE,不影响请求的发送。http的请求方法就为设置的错误值的大写,由服务器决定如何处理。如果对方法有限定可能会响应302,没有限定则可能会响应200。

    • res.request.method的值即这里设置的字符串。如果是小写的get,会自动转为大写。

    (2)url

    • 该参数必须设置,而且需要包括协议部分
    • 如果域名不存在http或者https服务,会报错
    • 可以直接处理https,也可以是http

    (3)params

    q = {'name':'zz'}
    # q = {'name':'zz','age':12}
    # q_2 = [('name','zz'),('age',22)]
    # q_3 = 'name=xx&age=12'
    res_1 = requests.request(method='GET', url='https://www.baidu.com', params=q)
    # https://www.baidu.com?name=zz
    res_2 = requests.request(method='GET', url='https://www.baidu.com?name=12', params=q)
    # https://www.baidu.com?name=12&name=zz
    

    作用:设置url中的请求参数,类型可以为字典或者元组的列表,或者字符串

    字典中的值会拼接到url中的params部分,如果未有参数,则先会添加?。如果已有参数,则直接追加,注意不会检查已有参数是否已经重名

    (4)data

    data_1 = 'abcd'	# abcd
    data_2 = {'name':'zz','age':12}	# name=zz&age=12
    data_3 = [('name','zz'),('age',12)] # name=zz&age=12
    

    作用:设置body部分携带的数据,类型可以为字符串、元组的列表和字典

    (5)json

    json_1 = 'abcd'	# b'"abcd"'
    json_2 = {'name':'zz','age':12}	# b'{"name": "zz", "age": 12}'
    json_3 = [('name','zz'),('age',12)]	# b'[["name", "zz"], ["age", 12]]'
    

    作用:设置body部分携带的数据,以json格式发送,类型可以为字符串、元组的列表和字典

    (6)headers

    headers = {'User-Agent':'zz','age':'12', 'Cookie':'name=zz; age=123'}
    

    作用:设置请求的头部字段,类型为字典,并且字典元素的键和值都必须是str类型,否则报错

    request方法自身默认会设置一些http请求头部字段,在指定headers参数时,会进行判断是否已设置字段,判断不区分大小写,如果重复则覆盖,如果不重复则追加字段

    如果覆盖,并且新设置的键和值替代之前的键和值。主要注意其键的大小写以新设置的为准

    headers的键可以任意设置,而非一定要是http协议规定的,同时可以直接在其中设置cookie

    (7)cookies

    cookies = {'name':'zz','age':'12'}
    

    作用:设置请求携带的cookie,类型为字典,并且字典元素的键和值都必须是str类型,否则报错

    (8)files

    upload_files = {'file': open('report.xls', 'rb')}
    r = requests.post(url, files=upload_files)
    

    作用:上传文件

    在读取文件时,注意务必使用'rb'即二进制模式读取,这样获取的bytes长度才是文件的长度。

    特定请求方法

    def get(url, params=None, **kwargs)
    def options(url, **kwargs)
    def head(url, **kwargs)
    def post(url, data=None, json=None, **kwargs)
    def put(url, data=None, **kwargs)
    def patch(url, data=None, **kwargs)
    def delete(url, **kwargs)
    

    请求信息

    print(res.request.url, type(res.request.url))
    print(res.request.method, type(res.request.method))
    print(res.request.headers, type(res.request.headers))
    print(res.request.body, type(res.request.body))
    print(res.request.hooks, type(res.request.hooks))
    

    (1)url和method

    这两个属性类型为字符串,并且一个正常的request方法调用其值不为空

    (2)headers

    1)从值的形式上来说,是字典形式,键和值都是字符串。但实际的数据类型为<class 'requests.structures.CaseInsensitiveDict'>

    2)其值往往也不为空,模块代码会默认设置和携带一些头部

    3)以下四种均输出,证明大小写不敏感

    if 'user-agent' in res.request.headers:
        print(1)
    if 'user-agent' in res.request.headers.keys():
        print(12)
    if 'User-Agent' in res.request.headers:
        print(13)
    if 'User-Agent' in res.request.headers.keys():
        print(134)
    

    4)对headers直接在pyqt等要求参数为字符串str的场景中必须使用str函数进行强转

    (3)body

    如果没有设置data或者json,其值为None,类型为NoneType

    在pyqt等要求参数为字符串str的场景中必须使用str函数进行强转

    如果设置了data或者json,其值为str类型

    (4)hooks

    属性类型为字典,字典只有一个元素,其键为response,值为一个列表,列表的元素为定义的钩子函数

    在pyqt等要求参数为字符串str的场景中必须使用str函数进行强转

    {'response': [<function print_url at 0x0000026BC320F0D0>, <function change_url at 0x0000026BC35D0700>]}
    

    响应信息

    (1)响应

    print(res, type(res))
    # <Response [302]> <class 'requests.models.Response'>
    
    • 请求执行之后会返回一个响应对象

    (2)headers

    作用:获取响应的头部字段信息

    其类似dict类型,可用通过索引取值,或者str函数转换,或者调用dict类型的方法

    如果取值没有该字段,会报错

    print(res.headers, type(res.headers))
    # {'Server': 'nginx/1.15.5', 'Date': 'Sat, 21 Aug 2021 21:10:41 GMT', 'Content-Type': 'text/html', 'Content-Length': '157', 'Connection': 'keep-alive'} <class 'requests.structures.CaseInsensitiveDict'>
    print(res.headers['Server'])
    print(res.headers.values())
    

    (3)url、raw、ok、is_redirect、reason、status_code

    print(res.url, type(res.url))
    print(res.raw, type(res.raw))
    print(res.ok, type(res.ok))
    print(res.is_redirect, type(res.is_redirect))
    print(res.reason, type(res.reason))
    print(res.status_code, type(res.status_code))
    '''
    https://www.baidu.com/ <class 'str'>
    <urllib3.response.HTTPResponse object at 0x0000018470426AF0> <class 'urllib3.response.HTTPResponse'>
    True <class 'bool'>
    False <class 'bool'>
    OK <class 'str'>
    200 <class 'int'>
    '''
    
    • url:str类型
    • raw:暂时未找到应用方式
    • ok:bool类型,判断是否为200
    • is_redirect:bool类型,判断是否为3xx
    • reason:str类型,状态描述
    • status_code:int类型,状态代码

    (4)encoding、apparent_encoding、cookies、history、

    print(res.encoding, type(res.encoding))
    print(res.apparent_encoding, type(res.apparent_encoding))
    print(res.cookies, type(res.cookies))
    print(res.history, type(res.history))
    '''
    ISO-8859-1 <class 'str'>
    utf-8 <class 'str'>
    <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]> <class 'requests.cookies.RequestsCookieJar'>
    [] <class 'list'>
    '''
    
    • encoding:编码,str类型
    • apparent_encoding:表现编码,str类型
    • cookies:自定义类型,可以通过其对象方法操作
    • history:历史,list类型
    print(res.text.encode(encoding=res.encoding).decode(res.apparent_encoding))
    print(res.content, type(res.content))
    print(res.links, type(res.links))
    '''
    xxx
    b'xxx' <class 'bytes'>
    {} <class 'dict'>
    '''
    
    • text:内容部分,str类型。其一般会进行字符编码传输,res.encoding指定传输编码。而apparent_encoding指定重新编码
      • 但注意res.encoding参数可能会为None,该请求会报错,所以需要先做判断
      • apparent_encoding一般直接指定为utf-8
    • context:内容部分,bytes字节类型
    • links:字典类型

    (6)elapsed、next、is_permanent_redirect

    print(res.elapsed, type(res.elapsed))
    print(res.next, type(res.next))
    print(res.is_permanent_redirect, type(res.is_permanent_redirect))
    '''
    0:00:00.230697 <class 'datetime.timedelta'>
    None <class 'NoneType'>
    False <class 'bool'>
    '''
    
    • elapsed:请求的响应时间
    • next:一般是重定向使用的路径
    • is_permanent_redirect:是否永久重定向
  • 相关阅读:
    [SCOI2003]严格N元树
    CF280 C. Game on Tree
    [HDU2281]Square Number
    [HDU5391]Zball in Tina Town
    [HDU3988]Harry Potter and the Hide Story
    [HDU5794]A Simple Chess
    [HDU5451]Best Solver
    [HDU1724]Ellipse
    [HDU6304]Chiaki Sequence Revisited
    [HDU6343]Graph Theory Homework
  • 原文地址:https://www.cnblogs.com/heibaimao123/p/16282809.html
Copyright © 2020-2023  润新知