例如:
import requests
import json
url = 'http://example.com/path/to/api'
data = {
'name': 'John',
'age': 30,
'gender': 'male'
}
headers = {'Content-type': 'application/json'}
response = requests.post(url, headers=headers, json=data)
print(response.status_code)
print(response.json())
這里通過json參數(shù)傳遞了一個字典類型的data數(shù)據(jù),在請求頭中設置Content-Type為application/json。requests會自動將json參數(shù)轉(zhuǎn)化為合法的JSON格式,并且將其作為請求體提交給服務器。注意,這里的json參數(shù)是requests庫中的內(nèi)置參數(shù)之一,表示將請求體數(shù)據(jù)序列化為JSON格式。
在服務器端收到上述POST請求時,可以使用request對象的json屬性來獲取提交過來的JSON數(shù)據(jù)。文章來源:http://www.zghlxwxcb.cn/news/detail-505433.html
需要注意的是,如果要使用requests庫發(fā)送JSON類型的數(shù)據(jù),就必須設置請求頭Content-Type為"application/json",否則服務端無法正確解析請求。文章來源地址http://www.zghlxwxcb.cn/news/detail-505433.html
到了這里,關(guān)于Python | 爬蟲的request.post如何傳遞json參數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!