Python is a powerful programming language, and the requests
library makes processing network requests simple and efficient. In this tutorial, we will show you how to use the Python requests library to initiate a GET request and parse the response data.
What is a GET request
GET
request is one of the HTTP request methods, mainly used to obtain data from the server. In Python, the requests
library can easily handle this request.
Initiate a simple GET request
The following is a basic example of using requests to initiate a GET request:
import requests
response = requests.get('https://www.google.com')
print(response.status_code)
print(response.text)
Parsing response data
The response of a GET request can be parsed in many ways, such as obtaining the status code, response headers, or response content. Here are some common methods:
Get Status Code
Returns the HTTP status code of the server response:
print(response.status_code)
Get Response Header
Returns the HTTP header information in the server response:
print(response.headers)
print(response.headers['Content-Encoding'])
Get the response content
Return the original binary data of the server response:
print(response.content)
Unlike response.text
, response.content
does not automatically decode the content, but provides it in raw byte form. If you need to save the content as a file (such as a picture or PDF file), you can directly write response.content
to the file.
Getting data in JSON format
Used to parse the response content returned by the server directly into a JSON object; this method is suitable for situations where the server returns data in JSON format, and it can help you easily parse and process JSON data.
json_data = response.json()
# 打印解析后的 JSON 数据
print(json_data)
# 访问具体字段
name = json_data['name']
Constructing URL Parameters
Constructing URL Parameters Manually
You can concatenate parameters directly into the URL; for example, if you need to add query parameters to a Google search request:
import requests
response = requests.get('https://www.google.com/search?q=完美代码')
print(response.url)
Use params keyword parameter
requests
provides the params
parameter, which allows you to pass URL parameters more conveniently. requests
will automatically handle encoding issues for you:
import requests
# 构建参数字典
params = {'q': "完美代码"}
response = requests.get('https://www.google.com/search',params=params)
print(response.url)
You can view the full URL generated by printing response.url
. Requests will automatically URL encode the parameters:
https://www.google.com/search?q=%E5%AE%8C%E7%BE%8E%E4%BB%A3%E7%A0%81