zoukankan      html  css  js  c++  java
  • python之requests库分析

    1.requests库发送请求时,params和data、json的区别

     params的时候之间接把参数加到url后面,只在get请求时使用,data、json是用在post请求,json是传递的json格式的数据

    params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    params是一个字典或者bytes类型,用来查询
    data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    data可以是一个字典或者元组或者bytes或者文件对象,用在请求的body
    json: (optional) json data to send in the body of the :class:`Request`.
    json用于请求body,且传输的是json格式数据

    2.requests库响应结果content和text、json区别
    text:
    Content of the response, in unicode 可以接收文本格式的响应报文,unicode编码
    json:Returns the json-encoded content of a response, if any
    注意:If the response body does not contain valid json 如果响应body不是json格式的会报错,所以只有当响应body是json格式才可以用此方式接收响应报文
    content:Content of the response, in bytes  接收bytes格式的报文,一般用来接收图片或者文件二进制
    text、json是属性方法,调用不需要加(),而json是普通方法,调用需要加()
    response.content
    response.text
    response.json()

    requests库response 响应内容
    r.url                      #获取请求url
    r.encoding                       #获取当前的编码
    r.encoding = 'utf-8'             #设置编码
    r.text                           #以encoding解析返回内容。字符串方式的响应体,会自动根据响应头部的字符编码进行解码。
    r.content                        #以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。
    
    r.headers                        #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
    
    r.status_code                     #响应状态码
    r.raw                             #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read()   
    r.ok                              # 查看r.ok的布尔值便可以知道是否登陆成功
     #*特殊方法*#
    r.json()                         #Requests中内置的JSON解码器,以json形式返回,前提返回的内容确保是json格式的,不然解析出错会抛异常
    r.raise_for_status()             #失败请求(非200响应)抛出异常

    基本身份认证(HTTP Basic Auth)
    import requests
    from requests.auth import HTTPBasicAuth
     
    r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))
    # r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd'))    # 简写
    print(r.json())


  • 相关阅读:
    TFS 安装遇到的问题
    批量将MP4 转换为 MP3
    sqlite like 通配符 ,匹配区分大小写(默认不区分大小写)
    AutoCAD 2007-2012 长度统计工具
    python27 ImportError: No module named site
    github push时,要求密码的问题
    sqlserver中自定义计算函数
    关于win10家庭版不能开启虚拟机的问题
    js的MD5实现
    高德各省行政区显示不同区别颜色(转)
  • 原文地址:https://www.cnblogs.com/qqxin/p/13380075.html
Copyright © 2011-2022 走看看