python requests post的使用方式
python模擬瀏覽器發(fā)送post請求
import requests
格式request.post
request.post(url, data, json, kwargs) # post請求格式 request.get(url, params, kwargs) # 對比get請求
發(fā)送post請求 傳參分為
- 表單(x-www-form-urlencoded)
- json(application/json)
data參數(shù)支持字典格式和字符串格式,字典格式用json.dumps()方法把data轉(zhuǎn)換為合法的json格式字符串 次方法需要導(dǎo)入json模塊;
import json json.dumps(data) # data轉(zhuǎn)換成json格式
或者將data參數(shù)賦值給post方法的json參數(shù),必須為合法json格式,否則沒用,如果有布爾值要小寫,不能有非Unicode字符。
表單方式的post請求(x-www-form-urlencoded)
import requests
url = "https://editor.net/"
data = {"key": "value"} # 字典 外層無引號
resp = requests.post(url,data=data)
print(resp.text)
json類型的post請求
import requests
url = "https://editor.net/"
data = '{"key": "value"}' # 字符串格式
resp = requests.post(url, data=data)
print(resp.text)
使用字典格式填寫參數(shù),傳遞時轉(zhuǎn)換為json格式
(1)json.dumps()方法轉(zhuǎn)換
import requests
import json
url = "https://editor.net/"
data = {"key": "value"}
resp = requests.post(url, data=json.dumps(data))
print(resp.text)
(2)將字典格式的data數(shù)據(jù)賦給post方法的json參數(shù)
import requests
import json
url = "https://editor.net/"
data = {"key": "value"}
resp = requests.post(url, json=data)
print(resp.text)
python requests post數(shù)據(jù)的幾個問題的解決
最近在用Requests做一個自動發(fā)送數(shù)據(jù)的小程序,使用的是Requests庫,在使用過程中,對于post數(shù)據(jù)的編碼有一些問題,查找很多資料,終于解決。
post數(shù)據(jù)的urlencode問題
我們一般post一個dict數(shù)據(jù)的時候,requests都會把這個dict里的數(shù)據(jù)進行urlencode,再進行發(fā)送。
但我發(fā)現(xiàn)他用的urlencode默認(rèn)是UTF-8編碼,如果我的網(wǎng)站程序只支持gb2312的urlencode怎么辦呢?
可以引入urllib中的urllib.parse.urlencode進行編碼。
from urllib.parse import urlencode
import requests
?
session.post('http://www.bac-domm.com', ? data=urlencode({'val':'中國人民'}, encoding='gb2312'), ?headers = head_content)避免數(shù)據(jù)被urlencode的問題
有時我們并不希望數(shù)據(jù)進行urlencode,怎么辦?
只要在post的data里拼接成字符串就可以了,當(dāng)然在拼接的時候要注意字符串的編碼問題,比如說含有中文時,就應(yīng)該把編碼設(shè)置為utf-8或gb2312
vld = 'val:中國人民'
session.post('http://www.bac-domm.com', ? data=vld.encode('utf-8'), ?headers = head_content)總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python+Tkinter實現(xiàn)股票K線圖的繪制
K線圖又稱蠟燭圖,常用說法是“K線”。K線是以每個分析周期的開盤價、最高價、最低價和收盤價繪制而成。本文將利用Python+Tkinter實現(xiàn)股票K線圖的繪制,需要的可以參考一下2022-08-08

