04_异步网络请求

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


📖 课程目标

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

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

场景对比

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

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

效率提升:10倍!

典型应用场景

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

📦 安装 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 fetch_page(url: str) -> str:
"""Send GET request to fetch page content"""
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
content = await response.text()
return content

# 使用
async def main():
content = await fetch_page("https://www.example.com")
print(content)

asyncio.run(main())

2. 发送POST请求

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

3. 添加请求头

1
2
3
4
5
6
7
8
9
10
async def request_with_headers(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 error_example():
for url in url_list:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
pass

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

为什么?

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

生活类比:餐厅点餐

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

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

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

需求

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

代码实现

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 crawl_page(session: aiohttp.ClientSession, url: str) -> Dict[str, any]:
"""爬取单个网页"""
try:
async with session.get(url, timeout=10) as response:
content = await response.text()

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

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

async def batch_crawl(url_list: List[str]) -> List[Dict]:
"""批量爬取多个网页"""
async with aiohttp.ClientSession() as session:
task_list = [crawl_page(session, url) for url in url_list]
result = await asyncio.gather(*task_list)
return result

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

result = await batch_crawl(urls)

for item in result:
if item["成功"]:
print(f"✅ {item['url']}: {item['content长度']}字节")
else:
print(f"❌ {item['url']}: {item['错误']}")

💡 实战案例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 query_weather(
session: aiohttp.ClientSession,
city: str
) -> Dict[str, any]:
"""查询单个城市的天气"""
try:
# 实际项目中替换为真实API
params = {"city": city}

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

if response.status == 200:
data = await response.json()
return {
"city": city,
"温度": data.get("temperature"),
"weather": data.get("weather"),
"成功": True
}
else:
return {
"city": city,
"错误": f"status_code: {response.status}",
"成功": False
}

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

async def batch_query_weather(city_list: List[str]) -> List[Dict]:
"""批量查询多个城市的天气"""
async with aiohttp.ClientSession() as session:
task_list = [query_weather(session, city) for city in city_list]
result = await asyncio.gather(*task_list)
return result

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

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

result = await batch_query_weather(city_list)

duration = time.time() - start_time

print(f"\n查询result(duration{duration:.2f}秒):")
for item in result:
if item["成功"]:
print(f"✅ {item['city']}: {item['温度']}°C, {item['weather']}")
else:
print(f"❌ {item['city']}: {item['错误']}")

完整代码在 04_examples.py 中!


🛡️ 错误处理和超时控制

1. 超时控制

1
2
3
4
5
6
7
async def request_with_timeout(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 request_with_retry(
session: aiohttp.ClientSession,
url: str,
max_retry: int = 3
) -> str:
"""失败后自动重试"""
for attempt_count in range(max_retry):
try:
async with session.get(url) as response:
if response.status == 200:
return await response.text()
else:
print(f"尝试 {attempt_count+1}/{max_retry}: 状态码 {response.status}")
except Exception as e:
print(f"尝试 {attempt_count+1}/{max_retry}: {e}")

if attempt_count < max_retry - 1:
await asyncio.sleep(1) # 等待1秒后重试

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

3. 异常处理

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

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

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

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

🎯 性能优化技巧

1. 限制并发数量

1
2
3
4
5
6
7
8
9
10
11
async def throttled_crawl(url_list: List[str], max_concurrency: int = 5):
"""限制同时请求的数量"""
semaphore = asyncio.Semaphore(max_concurrency)

async def limited_request(url: str):
async with semaphore:
return await crawl_page(url)

async with aiohttp.ClientSession() as session:
task_list = [limited_request(url) for url in url_list]
return await asyncio.gather(*task_list)

2. 连接池配置

1
2
3
4
5
6
7
8
9
10
11
async def optimized_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 efficient_batch_request(url_list: List[str]):
"""复用session和连接"""
async with aiohttp.ClientSession() as session:
# 所有请求复用同一个session
task_list = [session.get(url) for url in url_list]
response_list = await asyncio.gather(*task_list)

# 处理response
result = []
for response in response_list:
async with response:
content = await response.text()
result.append(content)

return result

📊 性能对比

场景:查询50个API

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

实际测试result

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

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

🎪 实战项目:newsaggregator

需求

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

功能

  1. 同时爬取多个news网站
  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 NewsAggregator:
"""News aggregator"""

def __init__(self, news_source_list: List[str]):
self.news_source_list = news_source_list

async def crawl_news_source(
self,
session: aiohttp.ClientSession,
url: str
) -> List[Dict]:
"""Crawl single news source"""
try:
async with session.get(url, timeout=10) as response:
html = await response.text()

# Parse HTML and extract news (simplified)
news_list = self._parse_news(html, url)

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

def _parse_news(self, html: str, source: str) -> List[Dict]:
"""Parse HTML and extract news"""
# 实际项目中使用 BeautifulSoup
# 这里简化处理
return [
{
"title": "示例news",
"链接": "https://example.com/news/1",
"source": source,
"时间": datetime.now()
}
]

async def aggregate_news(self) -> List[Dict]:
"""聚合所有news_sources"""
async with aiohttp.ClientSession() as session:
task_list = [
self.crawl_news_source(session, url)
for url in self.news_sources_list
]

result_list = await asyncio.gather(*task_list)

# 合并所有news
all_news = []
for news_list in result_list:
all_news.extend(news_list)

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

return all_news

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

aggregator = NewsAggregator(news_sources)
news_list = await aggregator.aggregate_news()

print(f"📰 共获取 {len(news_list)} 条新闻")
for news in news_list[:10]: # 显示前10条
print(f" - {news['title']} ({news['source']})")

📝 本课小结

核心知识点

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:
content = await response.text()
data = await response.json()

# 3. 发送POST请求
async with session.post(url, json=data) as response:
result = await response.json()

# 4. 批量请求
task_list = [crawl(url) for url in urls]
result = await asyncio.gather(*task_list)

# 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课:异步文件和data库操作

💪 课后练习

练习1:批量图片下载器

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

1
2
3
async def download_image(url: str, save_path: str):
# 你的代码
pass

练习2:API监控

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

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

练习3:带重试的爬虫

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

1
2
3
async def smart_crawl(url: str, max_retry: 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课示例代码:异步网络请求

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

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

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


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

class MockResponse:
"""模拟HTTPresponse"""

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)) # 模拟网络延迟

# 模拟不同的response
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"news标题 - {url}",
"content": "newscontent" * 100,
"author": "记者A"
})
else:
return MockResponse(200, {
"content": f"网页content - {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 fetch_page(url: str) -> str:
"""Send GET request to fetch page content"""
async with ClientSession() as session:
async with await session.get(url) as response:
content = await response.text()
return content


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

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

start_time = time.time()
content = await fetch_page(url)
duration = time.time() - start_time

print(f"✅ response:{content[:50]}...")
print(f"⏱️ duration:{duration:.2f}秒")

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


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

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


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

start_time = time.time()
result_list = []

async with ClientSession() as session:
# 一个一个爬取
for url in url_list:
print(f"📥 crawl:{url}")
result = await crawl_single_page(session, url)
result_list.append(result)

total_time = time.time() - start_time

print(f"\n✅ completed!共爬取 {len(result_list)} 个网页")
print(f"⏱️ total_time:{total_time:.2f}秒")


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

start_time = time.time()

async with ClientSession() as session:
# 同时爬取所有网页
task_list = [crawl_single_page(session, url) for url in url_list]

print(f"🚀 同时发起 {len(task_list)} 个请求...")
result_list = await asyncio.gather(*task_list)

total_time = time.time() - start_time

print(f"\n✅ completed!共爬取 {len(result_list)} 个网页")
print(f"⏱️ total_time:{total_time:.2f}秒")
print(f"💡 效率提升:约 {len(url_list)}倍!")


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

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

async with await session.get(url) as response:
if response.status == 200:
data = await response.json()
return {
"city": city,
"温度": data.get("temperature"),
"weather": data.get("weather"),
"湿度": data.get("humidity"),
"成功": True
}
else:
return {
"city": city,
"错误": f"status_code: {response.status}",
"成功": False
}

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


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

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

print(f"🌤️ 查询 {len(city_list)} 个城市的天气...")
start_time = time.time()

async with ClientSession() as session:
task_list = [query_weather(session, city) for city in city_list]
result_list = await asyncio.gather(*task_list)

total_time = time.time() - start_time

print(f"\n📊 查询result(duration {total_time:.2f}秒):")
print("-" * 50)

success_count = 0
for result in result_list:
if result["成功"]:
success_count += 1
print(f"✅ {result['city']:6s} | {result['温度']:2d}°C | "
f"{result['weather']:4s} | 湿度{result['湿度']}%")
else:
print(f"❌ {result['city']:6s} | 查询失败: {result['错误']}")

print("-" * 50)
print(f"成功率:{success_count}/{len(result_list)} ({success_count/len(result_list)*100:.0f}%)")


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

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

for attempt_count in range(max_retry):
try:
print(f" 尝试 {attempt_count + 1}/{max_retry}: {url}")

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

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

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

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


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

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

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

async with ClientSession() as session:
result = await request_with_retry(session, url, max_retry=3)

if result:
print(f"\n✅ 最终成功获取data")
else:
print(f"\n❌ 最终失败")

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


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

async def throttled_crawl(
session: MockSession,
url: str,
semaphore: asyncio.Semaphore,
number: int
) -> Dict[str, any]:
"""使用信号量限制并发的爬取"""
async with semaphore: # 获取许可
print(f" [{number}] 开始爬取: {url}")
result = await crawl_single_page(session, url)
print(f" [{number}] 完成爬取: {url}")
return result


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

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

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

print(f"🚀 开始爬取 {len(url_list)} 个网页(最多同时{max_concurrency}个)...")
start_time = time.time()

async with ClientSession() as session:
task_list = [
throttled_crawl(session, url, semaphore, i+1)
for i, url in enumerate(url_list)
]
result_list = await asyncio.gather(*task_list)

total_time = time.time() - start_time

print(f"\n✅ completed!total_time:{total_time:.2f}秒")
print(f"💡 观察:每次最多{max_concurrency}个请求在执行")


# ============================================
# 示例6:实战项目 - newsaggregator
# ============================================

class NewsAggregator:
"""News aggregator"""

def __init__(self, news_source_list: List[str]):
self.news_source_list = news_source_list

async def crawl_news_source(
self,
session: MockSession,
url: str
) -> List[Dict]:
"""Crawl single news source"""
try:
print(f" 📰 爬取news_source: {url}")

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

# 模拟提取多条新闻
news_list = [
{
"title": f"{data.get('title', 'news')} - {i+1}",
"作者": data.get("author", "未知"),
"source": url,
"content": data.get("content", "")[:50] + "..."
}
for i in range(3) # 每个源3条新闻
]

print(f" ✅ 获取 {len(news_list)} 条新闻")
return news_list
else:
print(f" ❌ status_code: {response.status}")
return []

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

async def aggregate_news(self) -> List[Dict]:
"""聚合所有news_sources"""
async with ClientSession() as session:
task_list = [
self.crawl_news_source(session, url)
for url in self.news_sources_list
]

result_list = await asyncio.gather(*task_list)

# 合并所有news
all_news = []
for news_list in result_list:
all_news.extend(news_list)

return all_news


async def example6_news_aggregation() -> None:
"""示例6:newsaggregator"""
print("\n" + "=" * 50)
print("📚 示例6:newsaggregator")
print("=" * 50)

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

print(f"📰 从 {len(news_sources)} 个news_sources聚合news...")
start_time = time.time()

aggregator = NewsAggregator(news_sources)
news_list = await aggregator.aggregate_news()

total_time = time.time() - start_time

print(f"\n📊 聚合result(duration {total_time:.2f}秒):")
print(f"共获取 {len(news_list)} 条新闻\n")

# 显示前5条
for i, news in enumerate(news_list[:5], 1):
print(f"{i}. {news['title']}")
print(f" 作者: {news['作者']} | source: {news['source']}")
print(f" {news['content']}\n")


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

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

# 运行所有示例
await example1_basic_request()

# 对比同步和异步
url_list = [
"https://example.com/page1",
"https://example.com/page2",
"https://example.com/page3",
"https://example.com/page4",
"https://example.com/page5",
]
await batch_crawl_sync(url_list)
await batch_crawl_async(url_list)

await example3_weather_query()
await example4_error_handling()
await example5_limit_concurrency()
await example6_news_aggregation()

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

🎯 核心代码:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
content = await response.text()
data = await response.json()

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

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

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

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


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