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轉換為合法的json格式字符串 次方法需要導入json模塊;
import json json.dumps(data) # data轉換成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ù),傳遞時轉換為json格式
(1)json.dumps()方法轉換
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默認是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里拼接成字符串就可以了,當然在拼接的時候要注意字符串的編碼問題,比如說含有中文時,就應該把編碼設置為utf-8或gb2312
vld = 'val:中國人民' session.post('http://www.bac-domm.com', ? data=vld.encode('utf-8'), ?headers = head_content)
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
解決pip安裝第三方庫,但PyCharm中卻無法識別的問題for mac
這篇文章主要介紹了解決pip安裝第三方庫,但PyCharm中卻無法識別的問題for mac,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-09-09