requests库的使用


一、get请求

import requests,json

def http_get(url,city):
    parmas = {"city":city}
    headers = {}
    proxies= {"http":"http://localhost:8080","https":"https://localhost:8080"}
    res = requests.get(url,params=parmas,headers=headers,timeout=3,proxies=proxies,verify=False)
    print(res.text)
    print(res.encoding)
    print(res.url)
    print(res.status_code)
    print(res.json())
    print(res.request.headers)

二、post请求  

1.请求头为'content-type':'application/x-www-form-urlencoded',data参数提交文本或字典都可以,headers为空时,data提交content-type默认也是application/x-www-form-urlencoded
2.请求头为'content-type':'application/json',使用json参数接收data 或者使用data=json.dumps({'f':10}))
3.请求头为content-type':'text/xml',data参数提交 ,通常用于上传xml格式文本等;将文本.encode("utf-8")编码为bytes类型上传,data=''.encode("utf-8"))
4.请求头为'content-type':'multipart/formdata',files参数提交,用于上传文件;通常Content-Type中除了Content-Type: multipart/form-data,还有个boundary=随机字符串,
该项的作用是当作提交内容的分隔符,构造files时用不到可以忽略,files = {"file":("test.jpg", open(r"D:\test\test.jpg",'rb')),"else1": (None,"xxx1"),"else2": (None,"xxx2") }
r = requests.post(url,files=files)

def http_post(url,city):
    parmas = {"citykey": city}
    headers = {}
    data = {"a":1}
    res = requests.get(url,params=parmas,headers=headers,data=data,timeout=3,verify=False)
    print(res.text)
    print(res.encoding)
    print(res.url)
    print(res.status_code)
    print(res.json())
    print(res.request.headers)
http_post("http://wthrcdn.etouch.cn/weather_mini","101010100")

本文参考:https://blog.csdn.net/watfe/article/details/122936187