SoFunction
Updated on 2024-11-17

Usage of python requests post

python simulates a browser sending a post request

import requests

specification

(url, data, json, kwargs) # post request format
(url, params, kwargs) # vs. get requests

Sending a post request Passing parameters is divided into

  • Forms (x-www-form-urlencoded)
  • json(application/json)

The data parameter supports dictionary format and string format, dictionary format with () method to convert data to legal json format string The sub-method needs to import the json module;

import json
(data) # data to json format

Or assign the data parameter to the json parameter of the post method, it must be in legal json format, otherwise it's useless, if there is a boolean value it should be lowercase, no non-Unicode characters.

Form-based post requests (x-www-form-urlencoded)

import requests
url = "/"
data = {"key": "value"} # Dictionary outer unquoted
resp = (url,data=data)
print()

json type post request

import requests
url = "/"
data = '{"key": "value"}' # String format
resp = (url, data=data)
print()

Fill in the parameters in dictionary format and convert them to json when passing them.

(1) () method conversion

import requests
import json
url = "/"
data = {"key": "value"}
resp = (url, data=(data))
print()

(2) Assign the dictionary-formatted data to the json parameter of the post method.

import requests
import json
url = "/"
data = {"key": "value"}
resp = (url, json=data)
print()

Solution to several problems with python requests post data

Recently in the use of Requests to do a small program to automatically send data, the use of the Requests library, in the process of using the encoding of the post data have some problems, find a lot of information, and finally solved.

urlencode problem with post data

When we generally post a dict, requests will urlencode the data in the dict before sending it.

But I found that the urlencode he used is UTF-8 by default, what if my website program only supports gb2312 urlencode?

can be introduced into urllib for coding.

from  import urlencode
import requests
 
('',   data=urlencode({'val':'The Chinese people'}, encoding='gb2312'),  headers = head_content)

Avoiding the problem of data being urlencoded

Sometimes we don't want the data to be urlencoded, what should we do?

As long as the data in the post spliced into a string on it, of course, in the splicing time to pay attention to the encoding of the string, for example, contains Chinese, the encoding should be set to utf-8 or gb2312

vld = 'val:Chinese people'
('',   data=('utf-8'),  headers = head_content)

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.