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
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))
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
ClientSession = MockSession
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")
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)}倍!")
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}%)")
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. 设置最大重试次数,避免无限重试")
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)
url_list = [f"https://example.com/page{i}" for i in range(1, 11)]
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}个请求在执行")
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) ]
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)
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")
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())
|