First, the installation of requests library
Requests library as a third-party library that needs to be installed
cmd mode, run PIP install requests
Second, before learning how to send a request, let's take a look at the requests library and see what he can do.
Print Dir (requests)
Third, analog send GET request
1. Send a GET request with no parameters
r = Requests.get (' https://api.github.com/events ')
Returns a response object that contains the contents of the object, through the Dir (r)
2. Send a GET request with parameters, such as a GET request link http://httpbin.org/get?key2=value2&key1=value1
You need to use the params keyword to write the argument to the params parameter, as follows:
Import REQUESTSR = Requests.get (' http://httpbin.org/get ', params={' key1 ': ' value1 ', ' key2 ': ' value2 '}) print R.url
Parameters can also be separated, as follows
Import requestspayload = {' Key1 ': ' value1 ', ' key2 ': ' value2 '}r = Requests.get (' Http://httpbin.org/get ', params=payload) Print R.url
The results of the above operations are:
3. Send a GET request with the request header, need to pass the headers parameter
Import requestsurl= ' https://api.github.com/some/endpoint ' headers = {' user-agent ': ' my-app/0.0.1 '}r = Requests.get ( Url,headers=headers)
Iv. analog sending of Post requests
1. When sending a POST request, you need to put the request parameter in the data parameter
url = ' http://httpbin.org/post ' payload = {' Key1 ': ' value1 ', ' key2 ': ' value2 '}r = requests.post (Url,data = payload)
Python Interface test requests library (i)