requests module - get request

Basic steps to send a GET request

Sending a GET request using Requests usually involves the following basic steps:

  1. Import the Requests module: First, we need to import the Requests module so that the Python program can use the functionality it provides.
  2. Construct request URL: determine the target URL to be accessed, and construct a complete request URL.
  3. Optional: Set request header information: Some websites may check request header information. In order to simulate browser access, we can set request header information.
  4. Send GET request: Use requests.get()the method to send a GET request, and optionally pass in request header information.
  5. Processing response: Get the response result returned by the server, which can be text, JSON data, binary data, etc.

example

Use Requests to send a GET request to Jianshu

import requests

# 设置请求头,模拟浏览器访问
headers = {
    
    
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}

# 简书的 URL
url = 'https://www.jianshu.com/'

# 发送 GET 请求
response = requests.get(url, headers=headers)

# 判断请求是否成功
if response.status_code == 200:
    # 获取页面源代码
    page_source = response.text
    print(page_source)
else:
    print('请求失败,状态码:', response.status_code)

Guess you like

Origin blog.csdn.net/m0_67268191/article/details/131754253