温馨提示×

Python requests模块示例代码

小亿
79
2024-01-04 16:07:35
栏目: 编程语言

以下是一个简单的示例代码,展示了如何使用Python的requests模块发送HTTP请求:

import requests

# 发送GET请求
response = requests.get("http://www.example.com")
print(response.status_code)  # 打印响应状态码
print(response.text)  # 打印响应内容

# 发送POST请求
data = {"username": "admin", "password": "123456"}
response = requests.post("http://www.example.com/login", data=data)
print(response.status_code)  # 打印响应状态码
print(response.json())  # 打印响应内容,假设返回的是JSON格式数据

# 发送带有请求头的GET请求
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
response = requests.get("http://www.example.com", headers=headers)
print(response.status_code)  # 打印响应状态码
print(response.text)  # 打印响应内容

上述代码中,首先使用requests.get()方法发送一个GET请求,返回的响应对象可以通过.status_code属性获取响应状态码,通过.text属性获取响应内容。

然后使用requests.post()方法发送一个POST请求,将表单数据以字典形式传递给data参数,同样可以通过.status_code属性和.json()方法获取响应状态码和内容。

最后发送带有请求头的GET请求,将请求头以字典形式传递给headers参数,同样可以通过.status_code属性和.text属性获取响应状态码和内容。

0