美文网首页
requests使用

requests使用

作者: 康凯_7f06 | 来源:发表于2019-03-24 09:57 被阅读0次

    中文文档 API: http://docs.python-requests.org/zh_CN/latest/index.html

    1.使用requests发送请求

        response = requests.get(url)

        response的常用方法:

            response.text:requests模块根据响应头对返回的数据进行解密(可能会解码错误),可以用response.encoding="utf-8"进行修改

            response.content:返回响应内容的bytes数据,使用decode()解码

            response.status_code:响应的状态码

            response.request.headers:请求的headers信息

            response.headers:响应的头部信息

    2.发送带有header的请求

        headers= {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)

    AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}

        requests.get(url, headers=headers)

    3.发送带参数的请求    

        params={"key":"value"}

        requests.get(url, params=params)

    4.发送post请求

        data={}

        headers={}

        requests.post(url, data=data, headers= headers)

    5.使用代理

    代理的作用:1)防止服务器识别为同一个ip访问

                          2)防止个人信息泄露

    proxies={

            "http":"http://...",

            "https":"htttps://..."

    }

    requests.get(url, proxies=proxies)

    6.使用session发送请求

        session = requests.session()

        responce = session.get(url)

        session可以记住服务器返回的cookie,能够实现会话保持

    7.requests技巧

        1)requests.utils.dict_from_cookiejar :将cookie对象转化为字典

    requests.utils.cookiejar_from_dict: 反之

         2)取消SSL证书验证

    response = requests.get(url, verify=False)

        3)设置超时时间

    response = requests.get(url, timeout=10)

        4)判断请求是否成功

    assert response.status_code == 200

        5)url地址解码

    requests.utils.unquote()

    相关文章

      网友评论

          本文标题:requests使用

          本文链接:https://www.haomeiwen.com/subject/bxvyvqtx.html