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
