python利用request发送post请求
1. post请求方式编码有3种:
application/x-www-form-urlencoded #最常见的post提交数据的方式,以form表单形式提交数据 application/json #以json格式提交数据 multipart/form-data #一般使用来上传文件(较少用)
2. post一贯的用法是:requests.post(url,data), 具体我们使用不同的编码方式来有所不同:
1)、传统表单post请求(x-www-form-urlencoded)
import requests,json url = 'http://httpbin.org/post' data = {'key1':'value1','key2':'value2'} r =requests.post(url,data) print(r.text)
2)Requests以json形式发送post请求,
import requests,json url_json = 'http://httpbin.org/post' data_json = json.dumps({'key1':'value1','key2':'value2'}) #dumps:将python对象解码为json数据 r_json = requests.post(url_json,data_json) print(r_json.text)
#post的body是json类型,也可以用json参数传入;先导入json模块,用dumps方法转化成json格式;返回结果,传到data里
3)Requests以multipart形式发送post请求
import requests,json url_mul = 'http://httpbin.org/post' files = {'file':open('E://report.txt','rb')} r = requests.post(url_mul,files=files) print(r.text)
3.实例:post-json
header值获取可以用fidder或burpsuit抓包。
# coding:utf-8 import requests url = "https://passport.cnblogs.com/user/signin" headers = { 'Connection': 'keep-alive', 'Content-Length': '123', 'Cache-Control': 'max-age=0', 'Origin':'https://passport.csdn.net', 'Upgrade-Insecure-Requests':'1', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Referer': 'https://passport.csdn.net/account/login?from=http://www.csdn.net', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cookie': '省略', } payload = {'username':'**', 'password':'**', 'lt':'**', 'execution':'e1s1', '_eventId':'submit', } r = requests.post(url, json=payload, headers=headers,verify=False) print r.json()
由于是https请求,直接发送请求可能会报错误:SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590),可以加个参数:verify=False,表示忽略对 SSL 证书的验证。
参考:https://www.cnblogs.com/android-it/p/9558751.html
https://blog.csdn.net/qq_36260310/article/details/78730829
为美好的生活奋斗!