一、以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)

  1. 若带上headers还访问不成功,碰到需要认证用户的,一般需要携带cookies,此处是自己登录成功后的cookies

headers = {
        'user-agent': '复制自己浏览器里的即可',
        'cookie': '复制自己浏览器里的即可',
    }
  1. 若访问成功,但是浏览器数据返回数据却是空的,可以考虑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数据的方法和可能出现的问题。