python之request post數據的方法


參考網站: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數據的方法和可能出現的問題。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM