Python 网络编程:使用 Requests 库进行 HTTP 请求的实战

前言

大家好!今天我们来聊聊 Python 网络编程中的一个重要工具 ——Requests 库。网络编程看起来可能有些复杂,但其实使用 Requests 库可以让我们轻松发送 HTTP 请求,并处理各种网络数据。记得我第一次用 Requests 库的时候,就被它的简洁和强大所折服。现在,让我们一起来学习如何使用 Requests 库进行 HTTP 请求吧!

1. 安装 Requests 库

首先,我们需要安装 Requests 库。如果你还没有安装,可以使用以下命令:

1
pip install requests

2. 发送 HTTP GET 请求

2.1 基本用法

发送一个简单的 HTTP GET 请求非常容易。下面的代码展示了如何获取一个网页的内容:

1
2
3
4
5
6
7
8
9
10
import requests

url = 'https://jsonplaceholder.typicode.com/posts'
response = requests.get(url)

# 检查请求是否成功
if response.status_code == 200:
print(response.text)
else:
print(f'请求失败,状态码:{response.status_code}')

2.2 添加查询参数

有时候我们需要在 GET 请求中添加查询参数。可以使用 params 参数来实现:

1
2
3
4
5
6
7
8
9
10
import requests

url = 'https://jsonplaceholder.typicode.com/posts'
params = {'userId': 1}
response = requests.get(url, params=params)

if response.status_code == 200:
print(response.json())
else:
print(f'请求失败,状态码:{response.status_code}')

3. 发送 HTTP POST 请求

3.1 基本用法

发送 POST 请求通常用于提交数据。我们可以使用 data 参数来传递表单数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import requests

url = 'https://jsonplaceholder.typicode.com/posts'
data = {
'title': 'foo',
'body': 'bar',
'userId': 1
}
response = requests.post(url, data=data)

if response.status_code == 201:
print(response.json())
else:
print(f'请求失败,状态码:{response.status_code}')

3.2 发送 JSON 数据

有时候我们需要以 JSON 格式发送数据,可以使用 json 参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import requests

url = 'https://jsonplaceholder.typicode.com/posts'
json_data = {
'title': 'foo',
'body': 'bar',
'userId': 1
}
response = requests.post(url, json=json_data)

if response.status_code == 201:
print(response.json())
else:
print(f'请求失败,状态码:{response.status_code}')

4. 处理响应

4.1 响应内容

Requests 库可以方便地处理各种响应内容,包括文本、JSON 和二进制数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
import requests

url = 'https://jsonplaceholder.typicode.com/posts/1'
response = requests.get(url)

# 文本内容
print(response.text)

# JSON内容
print(response.json())

# 二进制内容
print(response.content)

4.2 自定义请求头

有时候我们需要在请求中添加自定义头信息,可以使用 headers 参数:

1
2
3
4
5
6
7
8
9
10
11
12
import requests

url = 'https://jsonplaceholder.typicode.com/posts'
headers = {
'User-Agent': 'my-app/0.0.1'
}
response = requests.get(url, headers=headers)

if response.status_code == 200:
print(response.json())
else:
print(f'请求失败,状态码:{response.status_code}')

5. 实战示例:下载文件

我们可以使用 Requests 库来下载文件。以下代码展示了如何下载一个图片文件:

1
2
3
4
5
6
7
8
9
10
11
import requests

url = 'https://via.placeholder.com/150'
response = requests.get(url)

if response.status_code == 200:
with open('downloaded_image.png', 'wb') as file:
file.write(response.content)
print('文件下载成功!')
else:
print(f'请求失败,状态码:{response.status_code}')

结论

通过本文的介绍,我们了解了如何使用 Python 的 Requests 库进行 HTTP 请求。无论是发送 GET 请求、POST 请求,还是处理响应数据,Requests 库都为我们提供了简洁而强大的接口。希望大家能通过实践掌握这些技巧,编写出更加高效和健壮的网络程序。赶快动手试试吧,并别忘了关注我们的博客,收藏这篇文章,更多精彩内容等着你!