Learning the requests library - follow the official documentation

Send a GET request:

import requests
r=requests.get("http://www.kekenet.com/")

If you need to pass parameters, you can have the following methods:

import requests
r=requests.get("http://httpbin.org/get?key1=value1&key2=value2")

or

payload = {'key1': 'value1', 'key2': 'value2'}
r=requests.get("https://httpbin.org/get",params=payload)

The value in the payload can also be a list type, such as

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

Equivalent to accessing the url: https://httpbin.org/get?key1=value1&key2=value2&key2=value3

Custom request headers:

headers={'user-agent': 'my-app/0.0.1'}
r=requests.get("https://api.github.com/some/endpoint",headers=headers)

Read content:

If you are reading non-text data, you can use r.content to read binary data

If you need to read the content of the web page, you can use r.text, Requests will make an encoding guess based on the Http header, and choose an appropriate decoding method. You can use r.encoding to check the encoding method. If the returned web page content is garbled, you can modify the value of r.encoding by checking the header encoding of r.content and re-extract r.text, so that the correct result will be obtained. content.

 

r=requests.get( " http://www.kekenet.com/ " )
 print (r.text)#This is garbled code,
 print (r.encoding)#You can check the content encoding method speculated by Requests
r.encoding = " UTF-8 " #Modify r.encoding by viewing the encoding of the web page 
print (r.text)

 

Process json data:

There is a json decoder inside Requests, which can help you process json data

r=requests.get("https://api.github.com/events")
t=r.json()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325055579&siteId=291194637
Recommended