美文网首页
python常用库-Requests

python常用库-Requests

作者: 侯宇明 | 来源:发表于2019-07-29 16:55 被阅读0次

    1.安装

    import requests
    

    2.使用

    2.1非常简单的调用方式

    import requests
    
    r=requests.get('http://www.helloworld.com')
    
    r=requests.post("http://helloworld.com")
    
    r=requests.put("http://helloworld.com")
    
    r=requests.delete("http://helloworld.com")
    
    r=requests.head("http://helloworld.com")
    
    r=requests.options("http://helloworld.com")
    
    

    2.2返回内容

    r.status_code #响应状态码
    r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取
    r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩
    r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码
    r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
    r.json() #Requests中内置的JSON解码器
    r.raise_for_status() #失败请求(非200响应)抛出异常
    

    2.3常用请求-get

    import requests
    
    parm = {'a': 111, 'b': 222}
    
    r=requests.get('http://www.helloworld.com', params=parm, timeout=2) #可以将参数以dict形式传入,超时时间单位为秒
    
    

    2.4常用请求-post

    import requests
    import json
     
    data = {'some': 'data'}
    headers = {'content-type': 'application/json',
                      'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'
    }
    # post请求加header
    r = requests.post('https://www.helloworld.com', data=json.dumps(data), headers=headers)
    
    import requests
     
    url = 'https://www.helloworld.com'
    files = {'file': open('/*path*/test.txt', 'rb')}
    #files = {'file': ('test.txt', open('/*path*/test.txt', 'rb'))}     #显式的设置文件名
    r = requests.post(url, files=files)  #上传文件
    

    相关文章

      网友评论

          本文标题:python常用库-Requests

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