python之request post資料的方法
阿新 • • 發佈:2022-01-08
參考網站:https://blog.csdn.net/weixin_46129834/article/details/107182433
今天學習一下request的幾種post方式
一、以data的形式post
import requests def main(): post_data = { 'type': '', 'name': 'XXX', 'keywords': 'python' } url = "https://example.com" response = requests.post(url, data=post_data)print(response) # response=<200>說明訪問成功 print(response.text) #response.text和瀏覽器返回資料相同說明post資料成功 if __name__ == '__main__': main()
二、以Json資料的形式post
import requests import json def main(): post_data = { 'type': '', 'name': 'XXX', 'keywords': 'python' } url= "https://example.com" post_data = json.dumps(post_data) response = requests.post(url, json=post_data) print(response) # response=<200>說明訪問成功 print(response.text) #response.text和瀏覽器返回資料相同說明post資料成功 if __name__ == '__main__': main()
補充說明:
1. 若訪問不成功,即response不為200首先考慮URL訪問請求頭,最簡單的就是攜帶User-agent。
headers = { 'user-agent': '複製自己瀏覽器裡的即可', }
requests.post(url, post_data, headers=headers)
2. 若帶上headers還訪問不成功,碰到需要認證使用者的,一般需要攜帶cookies,此處是自己登入成功後的cookies
headers = { 'user-agent': '複製自己瀏覽器裡的即可', 'cookie': '複製自己瀏覽器裡的即可', }
3. 若訪問成功,但是瀏覽器資料返回資料卻是空的,可以考慮post的資料無效,那麼嘗試新增一下content-type
""" content-type: 1. text/plain;charset=UTF-8 2. application/json;charset:utf-8 --多用於以Json形式傳遞資料 3. application/x-www-form-urlencoded; charset=UTF-8 --多用於以data形式傳遞資料 :return: """ headers = { 'user-agent': '複製自己瀏覽器裡的即可', 'cookie': '複製自己瀏覽器裡的即可', 'content-type': '不一定非要與瀏覽器一致,可以試試以上3種', }
以上就是post資料的方法和可能出現的問題。