zoukankan      html  css  js  c++  java
  • 【python】requests库

    中文官方文档:https://docs.python-requests.org/zh_CN/latest/user/advanced.html#proxies

    requests是python实现的简单易用的HTTP库,属于python的第3方库。requests封装了HTTP请求的所有方法,使用方便简单,只需要根据不同的请求方式调用相对应的方法就可以完成发送网络请求的整个过程。

    requests库中的get、post、put、head、delete等方法都是通过调用requests.request方法实现的。

    1. get()方法

    requests是通过调用get()方法来完成发送get请求的。get()方法源码如下:

    def get(self, url, params, **kwargs):
        r"""Sends a GET request.
    
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary, list of tuples or bytes to send
            in the body of the :class:`Request`.
        :param **kwargs: Optional arguments that ``request`` takes.
        :return: :class:`Response <Response>` object
        :rtype: requests.Response
        """
    
        kwargs.setdefault('allow_redirects', True)
        return self.request('GET', url, **kwargs)

    params参数说明:

    • params需要传入字典dict类型的接口数据,如果数据类型是json需要先转成字典。

    • get请求中,通过params传递的参数会附加到url。如果使用data或json来发送接口参数,请求不会成功。(因为data或json参数不会附加到url)

    注意:基于get请求的特点,请求参数也可以直接跟在URL之后。

    2. post()方法

    requests是通过调用post()方法来完成发送post请求的。源码如下:

    def post(self, url, data=None, json=None, **kwargs):
        r"""Sends a POST request. Returns :class:`Response` object.
        
        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the :class:`Request`.
        :param **kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """
        
        return self.request('POST', url, data=data, json=json, **kwargs)

    何时使用data参数或json参数,需要根据实际的接口所支持的数据类型进行选择:

    1.data参数

    • 大多数post请求的接口默认支持参数类型Content-Type为application/x-www-form-urlencoded,这时请求的接口参数需要传递一个form表单,往往是通过构造一个字典来传递form表单的。

    • 所以当我们向服务器提交form表单时就可以使用data参数,它会接收一个字典类型的数据,存放到请求体中,然后发送给服务器。(参数需是字典类型)

    2.json参数

    • 访问的接口支持content_type为application/json格式的数据类型,就可以通过json来传递接口参数

    • json参数可以是字典也可以是json类型

    3. Response对象

    使用requests方法后,会返回一个response对象,其存储了服务器响应的内容。常用的响应信息如下:

    r.text #type:<class 'str'>,字符串方式的响应体,会自动根据响应头部的r.encoding进行解码
    r.content #字节方式的响应体,中文显示为字符,会自动为你解码 gzip 和 deflate 压缩
    r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取
    r.json() #type:<class 'dict'>,Requests中内置的JSON解码器,以json形式返回。前提返回的内容确保是json格式的,不然解析出错会抛异常
    
    r.encoding #如果响应header中不存在charset,则认为编码为ISO‐8859‐1 
    r.apparent_encoding    #从网页内容中分析出的响应内容编码方式(备选编码方式)
    #r.text返回中若有乱码,可设置为下面两种编码:
    r.encoding = 'utf-8' 
    r.encoding = r.apparent_encoding
    
    r.status_code #响应状态码
    r.raise_for_status() #失败请求(非200响应)抛出异常
    r.reason #状态原因
    
    r.url #最终的url
    r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
    r.request.headers #返回请求消息的报头
    r.cookies #返回cookies

    4. 其他用法

    1.上传文件

    import requests
     
    url = 'http://127.0.0.1:5000/upload'
    files = {'file': open('/home/lyb/sjzl.mpg', 'rb')}
    # files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))}     #显式的设置文件名
    
    r = requests.post(url, files=files)
    print(r.text)

    2.代理访问

    采集时为避免被封IP,经常会使用代理。可通过给requests方法提供proxies参数来配置代理,如下:

    import requests
     
    proxies = {
      "http": "http://10.10.1.10:3128",
      "https": "http://10.10.1.10:1080",
    }
    requests.get("http://www.zhidaow.com", proxies=proxies, timeout=6)
    # 通过timeout属性设置超时时间,一旦超过这个时间还没获得响应内容,就会提示错误
    
    # 如果代理需要账户和密码,则需这样:
    proxies = {
        "http": "http://user:pass@10.10.1.10:3128/",
    }
  • 相关阅读:
    面向对象、构造函数的区别
    写一个function,清除字符串前后的空格。(兼容所有浏览器)
    两个DIV高度自适应方法(左右两个DIV高度一样)
    js数组去重
    input框处理删除小图标的功能
    查找显示高亮
    JSON.parse()和JSON.stringify()
    jquery封装
    怎么理解HTML语义化
    html5语义化标签
  • 原文地址:https://www.cnblogs.com/mind18/p/12869574.html
Copyright © 2011-2022 走看看