您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“python requests post如何使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“python requests post如何使用”吧!
import requests
request.post(url, data, json, kwargs) # post請求格式 request.get(url, params, kwargs) # 對比get請求
表單(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字符。
import requests url = "https://editor.net/" data = {"key": "value"} # 字典 外層無引號 resp = requests.post(url,data=data) print(resp.text)
import requests url = "https://editor.net/" data = '{"key": "value"}' # 字符串格式 resp = requests.post(url, data=data) print(resp.text)
(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)
最近在用Requests做一個自動發(fā)送數(shù)據(jù)的小程序,使用的是Requests庫,在使用過程中,對于post數(shù)據(jù)的編碼有一些問題,查找很多資料,終于解決。
我們一般post一個dict數(shù)據(jù)的時候,requests都會把這個dict里的數(shù)據(jù)進行urlencode,再進行發(fā)送。
但我發(fā)現(xiàn)他用的urlencode默認是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,怎么辦?
只要在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)
到此,相信大家對“python requests post如何使用”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。