Python requests Module
Python requests is a commonly used HTTP request library that makes it easy to send HTTP requests to websites and get the response.
The requests module is more concise than the urllib module.
To send HTTP requests with requests you first need to import the requests module:
import requests
Once imported, you can send HTTP requests using the methods provided by requests to a specified URL, for example:
Example
Import the requests package
import
requests
Send the request
x
=
requests.
get
(
'https://www.runoob.com/'
)
Return the web page content
(
x.
text
)
Every requests call returns a response object containing the specific response information, such as the status code, response headers and response content:
print(response.status_code) # 获取响应状态码
print(response.headers) # 获取响应头
print(response.content) # 获取响应内容
More response information is as follows:
| Attribute or method | Description |
|---|---|
| apparent_encoding | Encoding method |
| close() | Close the connection to the server |
| content | Return the response content in bytes |
| cookies | Return a CookieJar object containing the cookies sent back by the server |
| elapsed | Return a timedelta object containing the amount of time elapsed between sending the request and the arrival of the response, which can be used to test response speed. For example, r.elapsed.microseconds indicates how many microseconds the response took to arrive. |
| encoding | The encoding used to decode r.text |
| headers | Return the response headers in dictionary format |
| history | Return a list of response objects containing the request history (url) |
| is_permanent_redirect | Return True if the response is a permanently redirected url, otherwise False |
| is_redirect | Return True if the response was redirected, otherwise False |
| iter_content() | Iterate over the response |
| iter_lines() | Iterate over the lines of the response |
| json() | Return the JSON object of the result (the result must be written in JSON format, otherwise an error is raised) |
| links | Return the parsed header links of the response |
| next | Return the PreparedRequest object of the next request in the redirect chain |
| ok | Check the value of "status_code"; return True if it is less than 400, otherwise False |
| raise_for_status() | If an error occurs, the method returns an HTTPError object |
| reason | A description of the response status, such as "Not Found" or "OK" |
| request | Return the request object for this response |
| status_code | Return the HTTP status code, such as 404 and 200 (200 is OK, 404 is Not Found) |
| text | Return the response content as unicode data |
| url | Return the URL of the response |
Example
Import the requests package
import
requests
Send the request
x
=
requests.
get
(
'https://www.runoob.com/'
)
Return the HTTP status code
(
x.
status_code
)
A description of the response status
(
x.
reason
)
Return the encoding
(
x.
apparent_encoding
)
The output is as follows:
200
OK
utf-8
Request a JSON data file and return the JSON content:
Example
Import the requests package
import
requests
Send the request
x
=
requests.
get
(
'https://www.runoob.com/try/ajax/json_demo.json'
)
Return the JSON data
(
x.
json
(
)
)
The output is as follows:
{'name': '网站', 'num': 3, 'sites': [{'name': 'Google', 'info': ['Android', 'Google 搜索', 'Google 翻译']}, {'name': 'Runoob', 'info': ['Runoob Tutorial', '菜鸟工具', '菜鸟微信']}, {'name': 'Taobao', 'info': ['淘宝', '网购']}]}
requests methods
The requests methods are listed below:
| Method | Description |
|---|---|
| delete(url, args) | Send a DELETE request to the specified url |
| get(url, params, args) | Send a GET request to the specified url |
| head(url, args) | Send a HEAD request to the specified url |
| patch(url, data, args) | Send a PATCH request to the specified url |
| post(url, data, json, args) | Send a POST request to the specified url |
| put(url, data, args) | Send a PUT request to the specified url |
| request(method, url, args) | Send the specified request method to the specified url |
Use requests.request() to send a get request:
Example
Import the requests package
import
requests
Send the request
x
=
requests.
request
(
'get'
,
'https://www.runoob.com/'
)
Return the web page content
(
x.
status_code
)
The output is as follows:
200
Set the request headers:
Example
Import the requests package
import
requests
kw
=
{
's'
:
'Python Tutorial'
}
Set the request headers
headers
=
{
"User-Agent"
:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}
params accepts a dictionary or string of query parameters; a dictionary is automatically converted to url encoding, so urlencode() is not needed
response
=
requests.
get
(
"https://www.runoob.com/"
,
params
=
kw
,
headers
=
headers
)
Check the response status code
(
response.
status_code
)
Check the character encoding in the response headers
(
response.
encoding
)
Check the full url address
(
response.
url
)
Check the response content; response.text returns data in Unicode format
(
response.
text
)
The output is as follows:
200
UTF-8
https://www.runoob.com/?s=python+%E6%95%99%E7%A8%8B
... 其他内容...
The post() method can send a POST request to a specified url; its general form is as follows:
requests.post(url, data={key: value}, json={key: value}, args)
-
url The request url.
-
data The parameter is a dictionary, list of tuples, bytes or file object to be sent to the specified url.
-
json The parameter is a JSON object to be sent to the specified url.
-
args are other parameters, such as cookies, headers, verify, etc.
Example
Import the requests package
import
requests
Send the request
x
=
requests.
post
(
'https://www.runoob.com/try/ajax/demo_post.php'
)
Return the web page content
(
x.
text
)
The output is as follows:
本内容是使用 POST 方法请求的。
请求时间:
2022-05-26 17:30:47
A post request with parameters:
Example
Import the requests package
import
requests
Form parameters named fname and lname
myobj
=
{
'fname'
:
'RUNOOB'
,
'lname'
:
'Boy'
}
Send the request
x
=
requests.
post
(
'https://www.runoob.com/try/ajax/demo_post2.php'
,
data
=
myobj
)
Return the web page content
(
x.
text
)
The output is as follows:
你好,RUNOOB Boy,今天过得怎么样?
Additional request parameters
When sending a request we can attach extra parameters, such as request headers, query parameters and a request body, for example:
headers = {'User-Agent': 'Mozilla/5.0'} # 设置请求头
params = {'key1': 'value1', 'key2': 'value2'} # 设置查询参数
data = {'username': 'example', 'password': '123456'} # 设置请求体
response = requests.post('https://www.runoob.com', headers=headers, params=params, data=data)
The code above sends a POST request with request headers, query parameters and a request body attached.
Besides the basic GET and POST requests, requests also supports other HTTP methods such as PUT, DELETE, HEAD, OPTIONS, etc.