python爬蟲使用requests發送post請求示例詳解
簡介
HTTP協議規定post提交的數據必須放在消息主體中,但是協議并沒有規定必須使用什么編碼方式。服務端通過是根據請求頭中的Content-Type字段來獲知請求中的消息主體是用何種方式進行編碼,再對消息主體進行解析。具體的編碼方式包括:
application/x-www-form-urlencoded 最常見post提交數據的方式,以form表單形式提交數據。application/json 以json串提交數據。multipart/form-data 一般使用來上傳文件。
一、 以form表單發送post請求
Reqeusts支持以form表單形式發送post請求,只需要將請求的參數構造成一個字典,然后傳給requests.post()的data參數即可。例:
# -*- coding: utf-8 -*-# author:Garyimport requestsurl = ’http://httpbin.org/post’ # 一個測試網站的urldata = {’key1’: ’value1’, ’key2’: ’value2’} # 你發送給這個的數據r = requests.post(url, data=data) # 使用requests的post方法,data接受你想發送的數據print(r.text) # 查看返回的內容
輸出
{ “args”: {}, “data”: “”, “files”: {}, #你提交的表單數據“form”: { “key1”: “value1”,“key2”: “value2” }, “headers”: { …… “Content-Type”: “application/x-www-form-urlencoded”, …… }, “json”: null, …… }
可以看到,請求頭中的Content-Type字段已設置為application/x-www-form-urlencoded,且data = {‘key1’: ‘value1’, ‘key2’: ‘value2’}以form表單的形式提交到服務端,服務端返回的form字段即是提交的數據。
二、 以json形式發送post請求
可以將一json串傳給requests.post()的data參數,
# -*- coding: utf-8 -*-# author:Garyimport requestsimport jsonurl = ’http://httpbin.org/post’ # 一個測試網站的urljson_data = json.dumps({’key1’: ’value1’, ’key2’: ’value2’}) # 你發送給這個的數據,數據格式轉為jsonr = requests.post(url, data=json_data) # 使用requests的post方法,data接受你想發送的數據print(r.text) # 查看返回的內容
輸出:
{ “args”: {}, “data”: “{”key2”: ”value2”, ”key1”: ”value1”}”, “files”: {}, “form”: {}, “headers”: { …… “Content-Type”: “application/json”, …… }, “json”: { “key1”: “value1”, “key2”: “value2” }, …… }
可以看到,請求頭的Content-Type設置為application/json,并將json_data這個json串提交到服務端中。
三、 以multipart形式發送post請求(上傳文件)
Requests也支持以multipart形式發送post請求,只需將一文件傳給requests.post()的files參數即可。
# -*- coding: utf-8 -*-# author:Garyimport requestsurl = ’http://httpbin.org/post’files = {’file’: open(’report.txt’, ’rb’)} # 目錄下得有report.txt文件才能上傳,rb是指以二進制格式打開一個文件用于只讀。r = requests.post(url, files=files) # 通過files參數指定你想發送的文件的內容print(r.text)
輸出:
{ “args”: {}, “data”: “”, “files”: { “file”: “Hello world!” }, “form”: {}, “headers”: {…… “Content-Type”: “multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a”, …… }, “json”: null, …… }
文本文件report.txt的內容只有一行:Hello world!,從請求的響應結果可以看到數據已上傳到服務端中。
到此這篇關于python爬蟲使用requests發送post請求示例詳解的文章就介紹到這了,更多相關python爬蟲使用requests發送post請求內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
