example_playwright.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. """
  2. 百度搜索示例 - 使用 Playwright 直接实现
  3. Baidu Search Example - Direct Playwright Implementation
  4. 功能:
  5. 1. 打开百度
  6. 2. 搜索"Python 教程"
  7. 3. 提取搜索结果数据并保存到 baidu.json
  8. 4. 保存完整页面 HTML 到 baidu_page.html
  9. 使用方法:
  10. python example_playwright.py
  11. """
  12. import asyncio
  13. import json
  14. from pathlib import Path
  15. from datetime import datetime
  16. from playwright.async_api import async_playwright
  17. async def baidu_search_task():
  18. """
  19. 百度搜索任务:搜索"Python 教程"并保存数据
  20. """
  21. print("\n" + "="*80)
  22. print("🚀 开始执行百度搜索任务 (Playwright 版本)")
  23. print("="*80 + "\n")
  24. # 项目根目录
  25. project_root = Path(__file__).parent
  26. # 用户数据目录(用于保存登录状态)
  27. user_data_dir = Path.home() / ".playwright_profiles" / "baidu_profile"
  28. user_data_dir.mkdir(parents=True, exist_ok=True)
  29. async with async_playwright() as p:
  30. try:
  31. # ============================================================
  32. # 步骤 1: 启动浏览器(使用持久化上下文)
  33. # ============================================================
  34. print("📌 步骤 1: 启动浏览器...")
  35. # 使用 launch_persistent_context 保持登录状态
  36. context = await p.chromium.launch_persistent_context(
  37. user_data_dir=str(user_data_dir),
  38. headless=False,
  39. viewport={"width": 1280, "height": 720}
  40. )
  41. # 获取或创建页面
  42. if context.pages:
  43. page = context.pages[0]
  44. else:
  45. page = await context.new_page()
  46. print("✅ 浏览器已启动\n")
  47. # ============================================================
  48. # 步骤 2: 导航到百度首页
  49. # ============================================================
  50. print("📌 步骤 2: 导航到百度...")
  51. await page.goto("https://www.baidu.com")
  52. await page.wait_for_load_state("networkidle")
  53. print("✅ 已打开百度首页\n")
  54. # 等待页面加载
  55. await asyncio.sleep(2)
  56. # ============================================================
  57. # 步骤 3: 搜索"Python 教程"
  58. # ============================================================
  59. print("📌 步骤 3: 搜索关键词...")
  60. # 方式1: 直接导航到搜索结果页面(推荐)
  61. search_keyword = "Python 教程"
  62. search_url = f"https://www.baidu.com/s?wd={search_keyword}"
  63. print(f"🔍 搜索关键词: {search_keyword}")
  64. await page.goto(search_url)
  65. await page.wait_for_load_state("networkidle")
  66. print("✅ 已导航到搜索结果页面\n")
  67. # 等待搜索结果加载
  68. print("⏳ 等待搜索结果加载...")
  69. await asyncio.sleep(3)
  70. # 滚动页面加载更多内容
  71. print("📜 滚动页面加载更多内容...")
  72. await page.mouse.wheel(0, 800) # 向下滚动
  73. await asyncio.sleep(2)
  74. print("✅ 搜索结果已加载\n")
  75. # ============================================================
  76. # 步骤 4: 提取搜索结果数据
  77. # ============================================================
  78. print("📌 步骤 4: 提取搜索结果数据...")
  79. # 使用 JavaScript 提取数据
  80. extract_js = """
  81. (function(){
  82. try {
  83. // 提取搜索结果
  84. const results = [];
  85. // 百度的搜索结果选择器
  86. const resultItems = document.querySelectorAll('#content_left > div[class*="result"]');
  87. console.log('找到搜索结果数量:', resultItems.length);
  88. resultItems.forEach((item, index) => {
  89. if (index >= 10) return; // 只提取前10个
  90. try {
  91. // 提取标题和链接
  92. const titleEl = item.querySelector('h3 a, .t a');
  93. const title = titleEl ? titleEl.textContent.trim() : '';
  94. const link = titleEl ? titleEl.href : '';
  95. // 提取摘要
  96. const summaryEl = item.querySelector('.c-abstract, .content-right_8Zs40');
  97. const summary = summaryEl ? summaryEl.textContent.trim() : '';
  98. // 提取来源
  99. const sourceEl = item.querySelector('.c-color-gray, .source_1Vdff');
  100. const source = sourceEl ? sourceEl.textContent.trim() : '';
  101. if (title || link) {
  102. results.push({
  103. index: index + 1,
  104. title: title,
  105. link: link,
  106. summary: summary.substring(0, 200), // 限制摘要长度
  107. source: source
  108. });
  109. }
  110. } catch (e) {
  111. console.error('提取单个结果失败:', e);
  112. }
  113. });
  114. return {
  115. success: true,
  116. count: results.length,
  117. keyword: 'Python 教程',
  118. timestamp: new Date().toISOString(),
  119. results: results
  120. };
  121. } catch (e) {
  122. return {
  123. success: false,
  124. error: e.message,
  125. stack: e.stack
  126. };
  127. }
  128. })()
  129. """
  130. data = await page.evaluate(extract_js)
  131. if data.get('success'):
  132. print(f"✅ 成功提取 {data.get('count', 0)} 条搜索结果")
  133. # 保存到 baidu.json
  134. json_file = project_root / "baidu.json"
  135. with open(json_file, 'w', encoding='utf-8') as f:
  136. json.dump(data, f, ensure_ascii=False, indent=2)
  137. print(f"✅ 数据已保存到: {json_file}\n")
  138. # 打印前3条结果预览
  139. if data.get('results'):
  140. print("📋 前3条结果预览:")
  141. for item in data['results'][:3]:
  142. print(f" {item.get('index')}. {item.get('title', '无标题')}")
  143. print(f" 链接: {item.get('link', '')[:60]}...")
  144. print(f" 来源: {item.get('source', '未知')}")
  145. print()
  146. else:
  147. print(f"⚠️ 数据提取失败: {data.get('error', '未知错误')}")
  148. # 保存错误信息
  149. error_data = {
  150. "success": False,
  151. "error": data.get('error'),
  152. "keyword": "Python 教程",
  153. "timestamp": datetime.now().isoformat()
  154. }
  155. json_file = project_root / "baidu.json"
  156. with open(json_file, 'w', encoding='utf-8') as f:
  157. json.dump(error_data, f, ensure_ascii=False, indent=2)
  158. print(f"⚠️ 错误信息已保存到: {json_file}\n")
  159. # ============================================================
  160. # 步骤 5: 保存完整页面 HTML
  161. # ============================================================
  162. print("📌 步骤 5: 保存完整页面 HTML...")
  163. html_content = await page.content()
  164. page_url = page.url
  165. page_title = await page.title()
  166. # 保存 HTML 文件
  167. html_file = project_root / "baidu_page.html"
  168. with open(html_file, 'w', encoding='utf-8') as f:
  169. # 添加一些元信息
  170. meta_info = f"""<!--
  171. 页面标题: {page_title}
  172. 页面URL: {page_url}
  173. 保存时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
  174. 搜索关键词: Python 教程
  175. -->
  176. """
  177. f.write(meta_info)
  178. f.write(html_content)
  179. print(f"✅ HTML 已保存到: {html_file}")
  180. print(f" 页面标题: {page_title}")
  181. print(f" 页面URL: {page_url}")
  182. print(f" HTML 大小: {len(html_content):,} 字符\n")
  183. # ============================================================
  184. # 任务完成
  185. # ============================================================
  186. print("="*80)
  187. print("🎉 任务完成!")
  188. print("="*80)
  189. print(f"📁 生成的文件:")
  190. print(f" 1. baidu.json - 搜索结果数据")
  191. print(f" 2. baidu_page.html - 完整页面HTML")
  192. print("="*80 + "\n")
  193. # 等待一下让用户看到结果
  194. print("⏳ 浏览器将在 5 秒后关闭...")
  195. await asyncio.sleep(5)
  196. except Exception as e:
  197. print(f"\n❌ 任务执行失败: {str(e)}")
  198. import traceback
  199. traceback.print_exc()
  200. finally:
  201. # 关闭浏览器
  202. await context.close()
  203. print("✅ 浏览器已关闭\n")
  204. async def main():
  205. """主函数"""
  206. await baidu_search_task()
  207. if __name__ == "__main__":
  208. # 运行任务
  209. asyncio.run(main())