python requests post的使用方式
python模擬瀏覽器發(fā)送post請(qǐng)求
import requests
格式request.post
request.post(url, data, json, kwargs) # post請(qǐng)求格式 request.get(url, params, kwargs) # 對(duì)比get請(qǐng)求
發(fā)送post請(qǐng)求 傳參分為
- 表單(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請(qǐng)求(x-www-form-urlencoded)
import requests
url = "https://editor.net/"
data = {"key": "value"} # 字典 外層無引號(hào)
resp = requests.post(url,data=data)
print(resp.text)
json類型的post請(qǐng)求
import requests
url = "https://editor.net/"
data = '{"key": "value"}' # 字符串格式
resp = requests.post(url, data=data)
print(resp.text)
使用字典格式填寫參數(shù),傳遞時(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ù)的幾個(gè)問題的解決
最近在用Requests做一個(gè)自動(dòng)發(fā)送數(shù)據(jù)的小程序,使用的是Requests庫(kù),在使用過程中,對(duì)于post數(shù)據(jù)的編碼有一些問題,查找很多資料,終于解決。
post數(shù)據(jù)的urlencode問題
我們一般post一個(gè)dict數(shù)據(jù)的時(shí)候,requests都會(huì)把這個(gè)dict里的數(shù)據(jù)進(jìn)行urlencode,再進(jìn)行發(fā)送。
但我發(fā)現(xiàn)他用的urlencode默認(rèn)是UTF-8編碼,如果我的網(wǎng)站程序只支持gb2312的urlencode怎么辦呢?
可以引入urllib中的urllib.parse.urlencode進(jìn)行編碼。
from urllib.parse import urlencode
import requests
?
session.post('http://www.bac-domm.com', ? data=urlencode({'val':'中國(guó)人民'}, encoding='gb2312'), ?headers = head_content)避免數(shù)據(jù)被urlencode的問題
有時(shí)我們并不希望數(shù)據(jù)進(jìn)行urlencode,怎么辦?
只要在post的data里拼接成字符串就可以了,當(dāng)然在拼接的時(shí)候要注意字符串的編碼問題,比如說含有中文時(shí),就應(yīng)該把編碼設(shè)置為utf-8或gb2312
vld = 'val:中國(guó)人民'
session.post('http://www.bac-domm.com', ? data=vld.encode('utf-8'), ?headers = head_content)總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python3 實(shí)現(xiàn)一行輸入,空格隔開的示例
今天小編就為大家分享一篇python3 實(shí)現(xiàn)一行輸入,空格隔開的示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-11-11
django使用圖片延時(shí)加載引起后臺(tái)404錯(cuò)誤
本文給大家介紹的是作者在Django中使用圖片的延時(shí)加載技術(shù)后引起后臺(tái)404錯(cuò)誤的問題以及解決思路和方法,有需要的小伙伴可以參考下2017-04-04
Python+Tkinter實(shí)現(xiàn)股票K線圖的繪制
K線圖又稱蠟燭圖,常用說法是“K線”。K線是以每個(gè)分析周期的開盤價(jià)、最高價(jià)、最低價(jià)和收盤價(jià)繪制而成。本文將利用Python+Tkinter實(shí)現(xiàn)股票K線圖的繪制,需要的可以參考一下2022-08-08

