04_异步网络请求

网络请求是异步编程最典型的应用场景。本课教你使用aiohttp库进行异步HTTP请求,实现批量爬虫、API调用等实战功能。同步方式下载50个文件需要25秒,异步只需1秒!我们将学习如何处理错误、设置超时、限制并发数,并完成两个真实项目:天气查询系统和新闻聚合器。学完后你将具备开发高性能网络应用的能力。


📖 课程目标

  • 学会使用 aiohttp 发送异步HTTP请求
  • 掌握批量爬取网页的技巧
  • 理解异步API调用的最佳实践
  • 学会处理网络错误和超时
  • 完成实战项目:天气查询系统

🎯 为什么需要异步网络请求?

场景对比

假设你要查询10个城市的天气,每个请求需要1秒:

方式耗时说明
同步方式10秒一个一个查询 😴
异步方式约1秒同时查询 ⚡

效率提升:10倍!

典型应用场景

  • 🕷️ 网络爬虫:批量抓取网页
  • 🔌 API调用:调用多个第三方服务
  • 📥 文件下载:批量下载资源
  • 📊 数据采集:实时监控多个数据源

📦 安装 aiohttp

1
2
3
4
5
# 激活虚拟环境
source ../.venv/bin/activate

# 安装 aiohttp
uv pip install aiohttp

🔧 基础用法

1. 发送GET请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import aiohttp
import asyncio

async def 获取网页(url: str) -> str:
"""发送GET请求,获取网页内容"""
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
内容 = await response.text()
return 内容

# 使用
async def main():
内容 = await 获取网页("https://www.example.com")
print(内容)

asyncio.run(main())

2. 发送POST请求

1
2
3
4
5
6
async def 发送数据(url: str, 数据: dict) -> dict:
"""发送POST请求"""
async with aiohttp.ClientSession() as session:
async with session.post(url, json=数据) as response:
结果 = await response.json()
return 结果

3. 添加请求头

1
2
3
4
5
6
7
8
9
10
async def 带请求头的请求(url: str) -> str:
"""添加自定义请求头"""
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json"
}

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
return await response.text()

🎪 核心概念

ClientSession:会话管理

1
2
3
4
5
6
7
8
9
10
11
12
13
# ❌ 错误方式:每次请求都创建session
async def 错误示例():
for url in url列表:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
pass

# ✅ 正确方式:复用session
async def 正确示例():
async with aiohttp.ClientSession() as session:
for url in url列表:
async with session.get(url) as response:
pass

为什么?

  • Session 会复用TCP连接
  • 减少连接开销
  • 提高性能

生活类比:餐厅点餐

1
2
3
4
5
错误方式:
每次点餐都重新排队 → 浪费时间

正确方式:
排一次队,点多个菜 → 高效

💡 实战案例1:批量爬取网页

需求

爬取多个网站的标题和内容长度。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import aiohttp
import asyncio
from typing import List, Dict

async def 爬取网页(session: aiohttp.ClientSession, url: str) -> Dict[str, any]:
"""爬取单个网页"""
try:
async with session.get(url, timeout=10) as response:
内容 = await response.text()

# 简单提取标题(实际项目用 BeautifulSoup)
标题 = "网页标题" # 简化处理

return {
"url": url,
"状态码": response.status,
"标题": 标题,
"内容长度": len(内容),
"成功": True
}
except Exception as e:
return {
"url": url,
"错误": str(e),
"成功": False
}

async def 批量爬取(url列表: List[str]) -> List[Dict]:
"""批量爬取多个网页"""
async with aiohttp.ClientSession() as session:
任务列表 = [爬取网页(session, url) for url in url列表]
结果 = await asyncio.gather(*任务列表)
return 结果

# 使用
async def main():
urls = [
"https://www.python.org",
"https://www.github.com",
"https://www.stackoverflow.com",
]

结果 = await 批量爬取(urls)

forin 结果:
if 项["成功"]:
print(f"✅ {项['url']}: {项['内容长度']}字节")
else:
print(f"❌ {项['url']}: {项['错误']}")

💡 实战案例2:天气查询系统

需求

查询多个城市的天气信息(模拟API)。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import aiohttp
import asyncio
import time
from typing import List, Dict

# 模拟天气API
WEATHER_API = "https://api.example.com/weather"

async def 查询天气(
session: aiohttp.ClientSession,
城市: str
) -> Dict[str, any]:
"""查询单个城市的天气"""
try:
# 实际项目中替换为真实API
params = {"city": 城市}

async with session.get(
WEATHER_API,
params=params,
timeout=5
) as response:

if response.status == 200:
数据 = await response.json()
return {
"城市": 城市,
"温度": 数据.get("temperature"),
"天气": 数据.get("weather"),
"成功": True
}
else:
return {
"城市": 城市,
"错误": f"状态码: {response.status}",
"成功": False
}

except asyncio.TimeoutError:
return {"城市": 城市, "错误": "请求超时", "成功": False}
except Exception as e:
return {"城市": 城市, "错误": str(e), "成功": False}

async def 批量查询天气(城市列表: List[str]) -> List[Dict]:
"""批量查询多个城市的天气"""
async with aiohttp.ClientSession() as session:
任务列表 = [查询天气(session, 城市) for 城市 in 城市列表]
结果 = await asyncio.gather(*任务列表)
return 结果

# 使用示例
async def main():
城市列表 = ["北京", "上海", "广州", "深圳", "杭州"]

print("🌤️ 开始查询天气...")
开始时间 = time.time()

结果 = await 批量查询天气(城市列表)

耗时 = time.time() - 开始时间

print(f"\n查询结果(耗时{耗时:.2f}秒):")
forin 结果:
if 项["成功"]:
print(f"✅ {项['城市']}: {项['温度']}°C, {项['天气']}")
else:
print(f"❌ {项['城市']}: {项['错误']}")

完整代码在 04_examples.py 中!


🛡️ 错误处理和超时控制

1. 超时控制

1
2
3
4
5
6
7
async def 带超时的请求(url: str) -> str:
"""设置超时时间"""
timeout = aiohttp.ClientTimeout(total=10) # 总超时10秒

async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url) as response:
return await response.text()

2. 重试机制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
async def 带重试的请求(
session: aiohttp.ClientSession,
url: str,
最大重试: int = 3
) -> str:
"""失败后自动重试"""
for 尝试次数 in range(最大重试):
try:
async with session.get(url) as response:
if response.status == 200:
return await response.text()
else:
print(f"尝试 {尝试次数+1}/{最大重试}: 状态码 {response.status}")
except Exception as e:
print(f"尝试 {尝试次数+1}/{最大重试}: {e}")

if 尝试次数 < 最大重试 - 1:
await asyncio.sleep(1) # 等待1秒后重试

raise Exception(f"请求失败,已重试{最大重试}次")

3. 异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
async def 安全的请求(url: str) -> Dict[str, any]:
"""全面的异常处理"""
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=10) as response:
内容 = await response.text()
return {"成功": True, "内容": 内容}

except asyncio.TimeoutError:
return {"成功": False, "错误": "请求超时"}

except aiohttp.ClientError as e:
return {"成功": False, "错误": f"网络错误: {e}"}

except Exception as e:
return {"成功": False, "错误": f"未知错误: {e}"}

🎯 性能优化技巧

1. 限制并发数量

1
2
3
4
5
6
7
8
9
10
11
async def 限流爬取(url列表: List[str], 最大并发: int = 5):
"""限制同时请求的数量"""
信号量 = asyncio.Semaphore(最大并发)

async def 受限请求(url: str):
async with 信号量:
return await 爬取网页(url)

async with aiohttp.ClientSession() as session:
任务列表 = [受限请求(url) for url in url列表]
return await asyncio.gather(*任务列表)

2. 连接池配置

1
2
3
4
5
6
7
8
9
10
11
async def 优化的Session():
"""配置连接池"""
connector = aiohttp.TCPConnector(
limit=100, # 最大连接数
limit_per_host=10, # 每个主机最大连接数
ttl_dns_cache=300 # DNS缓存时间
)

async with aiohttp.ClientSession(connector=connector) as session:
# 使用session...
pass

3. 使用连接复用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async def 高效批量请求(url列表: List[str]):
"""复用session和连接"""
async with aiohttp.ClientSession() as session:
# 所有请求复用同一个session
任务列表 = [session.get(url) for url in url列表]
响应列表 = await asyncio.gather(*任务列表)

# 处理响应
结果 = []
for 响应 in 响应列表:
async with 响应:
内容 = await 响应.text()
结果.append(内容)

return 结果

📊 性能对比

场景:查询50个API

方式每个请求耗时总耗时效率
同步(requests)0.5秒25秒基准
异步(aiohttp)0.5秒约1秒25倍

实际测试结果

1
2
3
4
5
6
7
8
9
10
11
同步方式:
请求1: 0.5秒
请求2: 0.5秒
...
请求50: 0.5秒
总计: 25秒

异步方式:
同时发起50个请求
等待最慢的完成
总计: 约1秒

🎪 实战项目:新闻聚合器

需求

从多个新闻网站抓取最新新闻。

功能

  1. 同时爬取多个新闻网站
  2. 提取标题和链接
  3. 按时间排序
  4. 错误处理和重试

代码框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import aiohttp
import asyncio
from typing import List, Dict
from datetime import datetime

class 新闻聚合器:
"""新闻聚合器"""

def __init__(self, 新闻源列表: List[str]):
self.新闻源列表 = 新闻源列表

async def 爬取新闻源(
self,
session: aiohttp.ClientSession,
url: str
) -> List[Dict]:
"""爬取单个新闻源"""
try:
async with session.get(url, timeout=10) as response:
html = await response.text()

# 解析HTML,提取新闻(简化处理)
新闻列表 = self._解析新闻(html, url)

return 新闻列表
except Exception as e:
print(f"❌ 爬取失败 {url}: {e}")
return []

def _解析新闻(self, html: str, 来源: str) -> List[Dict]:
"""解析HTML,提取新闻"""
# 实际项目中使用 BeautifulSoup
# 这里简化处理
return [
{
"标题": "示例新闻",
"链接": "https://example.com/news/1",
"来源": 来源,
"时间": datetime.now()
}
]

async def 聚合新闻(self) -> List[Dict]:
"""聚合所有新闻源"""
async with aiohttp.ClientSession() as session:
任务列表 = [
self.爬取新闻源(session, url)
for url in self.新闻源列表
]

结果列表 = await asyncio.gather(*任务列表)

# 合并所有新闻
所有新闻 = []
for 新闻列表 in 结果列表:
所有新闻.extend(新闻列表)

# 按时间排序
所有新闻.sort(key=lambda x: x["时间"], reverse=True)

return 所有新闻

# 使用
async def main():
新闻源 = [
"https://news1.com",
"https://news2.com",
"https://news3.com",
]

聚合器 = 新闻聚合器(新闻源)
新闻列表 = await 聚合器.聚合新闻()

print(f"📰 共获取 {len(新闻列表)} 条新闻")
for 新闻 in 新闻列表[:10]: # 显示前10条
print(f" - {新闻['标题']} ({新闻['来源']})")

📝 本课小结

核心知识点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 1. 创建session
async with aiohttp.ClientSession() as session:
# 2. 发送GET请求
async with session.get(url) as response:
内容 = await response.text()
数据 = await response.json()

# 3. 发送POST请求
async with session.post(url, json=数据) as response:
结果 = await response.json()

# 4. 批量请求
任务列表 = [爬取(url) for url in urls]
结果 = await asyncio.gather(*任务列表)

# 5. 超时控制
timeout = aiohttp.ClientTimeout(total=10)
async with aiohttp.ClientSession(timeout=timeout) as session:
pass

最佳实践

  1. ✅ 复用 ClientSession
  2. ✅ 设置合理的超时时间
  3. ✅ 添加错误处理和重试
  4. ✅ 限制并发数量(避免被封)
  5. ✅ 添加请求头(模拟浏览器)

常见陷阱

  1. ❌ 每次请求都创建新session
  2. ❌ 不设置超时(可能卡死)
  3. ❌ 不处理异常(程序崩溃)
  4. ❌ 并发数太大(被服务器封禁)

🎯 下一步

  1. 运行 04_examples.py 查看完整示例
  2. 尝试爬取真实网站(注意遵守robots.txt)
  3. 完成课后练习题
  4. 准备学习第5课:异步文件和数据库操作

💪 课后练习

练习1:批量图片下载器

编写一个异步图片下载器,同时下载多张图片。

1
2
3
async def 下载图片(url: str, 保存路径: str):
# 你的代码
pass

练习2:API监控

编写一个程序,定时检查多个API的可用性。

1
2
3
async def 检查API(url: str) -> bool:
# 你的代码
pass

练习3:带重试的爬虫

实现一个带重试机制的网页爬虫。

1
2
3
async def 智能爬取(url: str, 最大重试: int = 3):
# 你的代码
pass

答案在 练习答案.py 中! 😊

04_examples.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
"""
第4课示例代码:异步网络请求

注意:本示例使用模拟数据,不需要真实网络连接
如需测试真实网络请求,请取消注释相关代码

运行方式:
python 04_examples.py
"""

import asyncio
import time
from typing import List, Dict, Optional
import random


# ============================================
# 模拟 aiohttp(用于演示,不需要安装aiohttp)
# ============================================

class MockResponse:
"""模拟HTTP响应"""

def __init__(self, status: int, data: dict):
self.status = status
self._data = data

async def text(self) -> str:
await asyncio.sleep(0.1) # 模拟网络延迟
return str(self._data)

async def json(self) -> dict:
await asyncio.sleep(0.1) # 模拟网络延迟
return self._data

async def __aenter__(self):
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
pass


class MockSession:
"""模拟HTTP会话"""

async def get(self, url: str, **kwargs) -> MockResponse:
"""模拟GET请求"""
await asyncio.sleep(random.uniform(0.3, 0.8)) # 模拟网络延迟

# 模拟不同的响应
if "weather" in url:
return MockResponse(200, {
"temperature": random.randint(15, 30),
"weather": random.choice(["晴天", "多云", "小雨"]),
"humidity": random.randint(40, 80)
})
elif "news" in url:
return MockResponse(200, {
"title": f"新闻标题 - {url}",
"content": "新闻内容" * 100,
"author": "记者A"
})
else:
return MockResponse(200, {
"content": f"网页内容 - {url}",
"length": random.randint(1000, 5000)
})

async def post(self, url: str, **kwargs) -> MockResponse:
"""模拟POST请求"""
await asyncio.sleep(random.uniform(0.3, 0.8))
return MockResponse(200, {"success": True, "message": "提交成功"})

async def __aenter__(self):
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
pass


# 使用模拟的session(如果安装了aiohttp,可以替换为真实的)
ClientSession = MockSession


# ============================================
# 示例1:基础GET请求
# ============================================

async def 获取网页(url: str) -> str:
"""发送GET请求,获取网页内容"""
async with ClientSession() as session:
async with await session.get(url) as response:
内容 = await response.text()
return 内容


async def 示例1_基础请求() -> None:
"""示例1:基础的GET请求"""
print("\n" + "=" * 50)
print("📚 示例1:基础GET请求")
print("=" * 50)

url = "https://www.example.com"
print(f"📥 请求:{url}")

开始时间 = time.time()
内容 = await 获取网页(url)
耗时 = time.time() - 开始时间

print(f"✅ 响应:{内容[:50]}...")
print(f"⏱️ 耗时:{耗时:.2f}秒")

print("\n💡 关键点:")
print(" 1. 使用 async with 管理session")
print(" 2. 使用 await 等待响应")
print(" 3. response.text() 获取文本内容")


# ============================================
# 示例2:批量请求 - 同步 vs 异步
# ============================================

async def 爬取单个网页(session: MockSession, url: str) -> Dict[str, any]:
"""爬取单个网页"""
try:
async with await session.get(url) as response:
内容 = await response.text()
return {
"url": url,
"状态码": response.status,
"内容长度": len(内容),
"成功": True
}
except Exception as e:
return {
"url": url,
"错误": str(e),
"成功": False
}


async def 批量爬取_同步方式(url列表: List[str]) -> None:
"""同步方式:一个一个爬取"""
print("\n" + "=" * 50)
print("📚 示例2A:批量爬取 - 同步方式")
print("=" * 50)

开始时间 = time.time()
结果列表 = []

async with ClientSession() as session:
# 一个一个爬取
for url in url列表:
print(f"📥 爬取:{url}")
结果 = await 爬取单个网页(session, url)
结果列表.append(结果)

总耗时 = time.time() - 开始时间

print(f"\n✅ 完成!共爬取 {len(结果列表)} 个网页")
print(f"⏱️ 总耗时:{总耗时:.2f}秒")


async def 批量爬取_异步方式(url列表: List[str]) -> None:
"""异步方式:同时爬取"""
print("\n" + "=" * 50)
print("📚 示例2B:批量爬取 - 异步方式")
print("=" * 50)

开始时间 = time.time()

async with ClientSession() as session:
# 同时爬取所有网页
任务列表 = [爬取单个网页(session, url) for url in url列表]

print(f"🚀 同时发起 {len(任务列表)} 个请求...")
结果列表 = await asyncio.gather(*任务列表)

总耗时 = time.time() - 开始时间

print(f"\n✅ 完成!共爬取 {len(结果列表)} 个网页")
print(f"⏱️ 总耗时:{总耗时:.2f}秒")
print(f"💡 效率提升:约 {len(url列表)}倍!")


# ============================================
# 示例3:天气查询系统
# ============================================

async def 查询天气(session: MockSession, 城市: str) -> Dict[str, any]:
"""查询单个城市的天气"""
try:
url = f"https://api.weather.com/weather?city={城市}"

async with await session.get(url) as response:
if response.status == 200:
数据 = await response.json()
return {
"城市": 城市,
"温度": 数据.get("temperature"),
"天气": 数据.get("weather"),
"湿度": 数据.get("humidity"),
"成功": True
}
else:
return {
"城市": 城市,
"错误": f"状态码: {response.status}",
"成功": False
}

except Exception as e:
return {
"城市": 城市,
"错误": str(e),
"成功": False
}


async def 示例3_天气查询() -> None:
"""示例3:天气查询系统"""
print("\n" + "=" * 50)
print("📚 示例3:天气查询系统")
print("=" * 50)

城市列表 = ["北京", "上海", "广州", "深圳", "杭州", "成都", "武汉", "西安"]

print(f"🌤️ 查询 {len(城市列表)} 个城市的天气...")
开始时间 = time.time()

async with ClientSession() as session:
任务列表 = [查询天气(session, 城市) for 城市 in 城市列表]
结果列表 = await asyncio.gather(*任务列表)

总耗时 = time.time() - 开始时间

print(f"\n📊 查询结果(耗时 {总耗时:.2f}秒):")
print("-" * 50)

成功数 = 0
for 结果 in 结果列表:
if 结果["成功"]:
成功数 += 1
print(f"✅ {结果['城市']:6s} | {结果['温度']:2d}°C | "
f"{结果['天气']:4s} | 湿度{结果['湿度']}%")
else:
print(f"❌ {结果['城市']:6s} | 查询失败: {结果['错误']}")

print("-" * 50)
print(f"成功率:{成功数}/{len(结果列表)} ({成功数/len(结果列表)*100:.0f}%)")


# ============================================
# 示例4:错误处理和重试
# ============================================

async def 带重试的请求(
session: MockSession,
url: str,
最大重试: int = 3
) -> Optional[str]:
"""失败后自动重试的请求"""

for 尝试次数 in range(最大重试):
try:
print(f" 尝试 {尝试次数 + 1}/{最大重试}: {url}")

async with await session.get(url) as response:
if response.status == 200:
内容 = await response.text()
print(f" ✅ 成功!")
return 内容
else:
print(f" ❌ 状态码: {response.status}")

except Exception as e:
print(f" ❌ 错误: {e}")

# 如果不是最后一次尝试,等待后重试
if 尝试次数 < 最大重试 - 1:
等待时间 = (尝试次数 + 1) * 0.5 # 递增等待时间
print(f" ⏳ 等待 {等待时间}秒 后重试...")
await asyncio.sleep(等待时间)

print(f" ❌ 请求失败,已重试 {最大重试} 次")
return None


async def 示例4_错误处理() -> None:
"""示例4:错误处理和重试机制"""
print("\n" + "=" * 50)
print("📚 示例4:错误处理和重试机制")
print("=" * 50)

url = "https://unstable-api.com/data"

print(f"📥 请求可能不稳定的API: {url}")

async with ClientSession() as session:
结果 = await 带重试的请求(session, url, 最大重试=3)

if 结果:
print(f"\n✅ 最终成功获取数据")
else:
print(f"\n❌ 最终失败")

print("\n💡 关键点:")
print(" 1. 使用 try-except 捕获异常")
print(" 2. 失败后等待一段时间再重试")
print(" 3. 设置最大重试次数,避免无限重试")


# ============================================
# 示例5:限制并发数量
# ============================================

async def 受限爬取(
session: MockSession,
url: str,
信号量: asyncio.Semaphore,
编号: int
) -> Dict[str, any]:
"""使用信号量限制并发的爬取"""
async with 信号量: # 获取许可
print(f" [{编号}] 开始爬取: {url}")
结果 = await 爬取单个网页(session, url)
print(f" [{编号}] 完成爬取: {url}")
return 结果


async def 示例5_限制并发() -> None:
"""示例5:限制并发数量"""
print("\n" + "=" * 50)
print("📚 示例5:限制并发数量(避免被封)")
print("=" * 50)

# 生成10个URL
url列表 = [f"https://example.com/page{i}" for i in range(1, 11)]

# 创建信号量:最多同时3个请求
最大并发 = 3
信号量 = asyncio.Semaphore(最大并发)

print(f"🚀 开始爬取 {len(url列表)} 个网页(最多同时{最大并发}个)...")
开始时间 = time.time()

async with ClientSession() as session:
任务列表 = [
受限爬取(session, url, 信号量, i+1)
for i, url in enumerate(url列表)
]
结果列表 = await asyncio.gather(*任务列表)

总耗时 = time.time() - 开始时间

print(f"\n✅ 完成!总耗时:{总耗时:.2f}秒")
print(f"💡 观察:每次最多{最大并发}个请求在执行")


# ============================================
# 示例6:实战项目 - 新闻聚合器
# ============================================

class 新闻聚合器:
"""新闻聚合器"""

def __init__(self, 新闻源列表: List[str]):
self.新闻源列表 = 新闻源列表

async def 爬取新闻源(
self,
session: MockSession,
url: str
) -> List[Dict]:
"""爬取单个新闻源"""
try:
print(f" 📰 爬取新闻源: {url}")

async with await session.get(url) as response:
if response.status == 200:
数据 = await response.json()

# 模拟提取多条新闻
新闻列表 = [
{
"标题": f"{数据.get('title', '新闻')} - {i+1}",
"作者": 数据.get("author", "未知"),
"来源": url,
"内容": 数据.get("content", "")[:50] + "..."
}
for i in range(3) # 每个源3条新闻
]

print(f" ✅ 获取 {len(新闻列表)} 条新闻")
return 新闻列表
else:
print(f" ❌ 状态码: {response.status}")
return []

except Exception as e:
print(f" ❌ 错误: {e}")
return []

async def 聚合新闻(self) -> List[Dict]:
"""聚合所有新闻源"""
async with ClientSession() as session:
任务列表 = [
self.爬取新闻源(session, url)
for url in self.新闻源列表
]

结果列表 = await asyncio.gather(*任务列表)

# 合并所有新闻
所有新闻 = []
for 新闻列表 in 结果列表:
所有新闻.extend(新闻列表)

return 所有新闻


async def 示例6_新闻聚合() -> None:
"""示例6:新闻聚合器"""
print("\n" + "=" * 50)
print("📚 示例6:新闻聚合器")
print("=" * 50)

新闻源 = [
"https://news1.com/api/news",
"https://news2.com/api/news",
"https://news3.com/api/news",
"https://news4.com/api/news",
]

print(f"📰 从 {len(新闻源)} 个新闻源聚合新闻...")
开始时间 = time.time()

聚合器 = 新闻聚合器(新闻源)
新闻列表 = await 聚合器.聚合新闻()

总耗时 = time.time() - 开始时间

print(f"\n📊 聚合结果(耗时 {总耗时:.2f}秒):")
print(f"共获取 {len(新闻列表)} 条新闻\n")

# 显示前5条
for i, 新闻 in enumerate(新闻列表[:5], 1):
print(f"{i}. {新闻['标题']}")
print(f" 作者: {新闻['作者']} | 来源: {新闻['来源']}")
print(f" {新闻['内容']}\n")


# ============================================
# 主程序
# ============================================

async def main() -> None:
"""主程序:运行所有示例"""
print("🎓 第4课:异步网络请求")
print("=" * 50)

# 运行所有示例
await 示例1_基础请求()

# 对比同步和异步
url列表 = [
"https://example.com/page1",
"https://example.com/page2",
"https://example.com/page3",
"https://example.com/page4",
"https://example.com/page5",
]
await 批量爬取_同步方式(url列表)
await 批量爬取_异步方式(url列表)

await 示例3_天气查询()
await 示例4_错误处理()
await 示例5_限制并发()
await 示例6_新闻聚合()

# 总结
print("\n" + "=" * 50)
print("🎉 第4课完成!")
print("=" * 50)
print("""
📚 你学到了什么?
1. 使用 aiohttp 发送异步HTTP请求
2. 批量爬取网页,效率提升数倍
3. 错误处理和重试机制
4. 限制并发数量,避免被封
5. 实战项目:天气查询、新闻聚合

🎯 核心代码:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
内容 = await response.text()
数据 = await response.json()

💡 最佳实践:
1. 复用 ClientSession
2. 设置超时时间
3. 添加错误处理和重试
4. 限制并发数量
5. 添加请求头

⚠️ 注意事项:
1. 遵守网站的 robots.txt
2. 不要过度请求(避免被封)
3. 添加合理的延迟
4. 处理各种异常情况

💪 动手练习:
1. 安装真实的 aiohttp:uv pip install aiohttp
2. 尝试爬取真实网站
3. 实现图片批量下载器
4. 完成课后练习题

🎯 下一步:
学习异步文件和数据库操作(第5课)
""")


if __name__ == "__main__":
# 运行主程序
asyncio.run(main())