# example.py 使用说明 ## 📋 功能说明 `example.py` 是一个完整的小红书搜索示例,展示了如何使用 `baseClassTools.py` 实现实际的自动化任务。 ### 实现的功能 1. ✅ 打开小红书网站 2. ✅ 自动检测是否需要登录 3. ✅ 等待用户手动登录(如果需要) 4. ✅ 搜索关键词"健身美女" 5. ✅ 提取搜索结果数据(标题、作者、链接等) 6. ✅ 保存数据到 `xhs.json` 文件 7. ✅ 保存完整页面 HTML 到 `xiaohongshu_page.html` 文件 8. ✅ 自动保存登录状态(下次运行无需重新登录) --- ## 🚀 快速开始 ### 1. 运行示例 ```bash # 在项目根目录下运行 python example.py ``` ### 2. 首次运行流程 ``` 🚀 开始执行小红书搜索任务 ================================================================================ 📌 步骤 1: 初始化浏览器会话... ✅ 浏览器会话已初始化 📌 步骤 2: 导航到小红书... ✅ 导航到 https://www.xiaohongshu.com 📌 步骤 3: 检查登录状态... ⚠️ 检测到需要登录 ⏸️ 请在浏览器窗口中完成登录操作 ============================================================ ⏸️ WAITING FOR USER ACTION ============================================================ 📝 请在浏览器中登录小红书 (Please login to Xiaohongshu) ⏱️ Timeout: 300 seconds 👉 Please complete the action in the browser window 👉 Press ENTER when done, or wait for timeout ============================================================ [在浏览器中完成登录后,按回车继续...] ✅ 用户已完成登录 📌 步骤 4: 搜索关键词... 🔍 搜索关键词: 健身美女 ✅ 已导航到搜索结果页面 ⏳ 等待搜索结果加载... 📜 滚动页面加载更多内容... ✅ 搜索结果已加载 📌 步骤 5: 提取搜索结果数据... ✅ 成功提取 15 条搜索结果 ✅ 数据已保存到: /path/to/project/xhs.json 📋 前3条结果预览: 1. 健身美女的日常训练 作者: 小红书用户 链接: https://www.xiaohongshu.com/explore/... 2. 健身房打卡 作者: 健身达人 链接: https://www.xiaohongshu.com/explore/... 3. 健身穿搭分享 作者: 时尚博主 链接: https://www.xiaohongshu.com/explore/... 📌 步骤 6: 保存完整页面 HTML... ✅ HTML 已保存到: /path/to/project/xiaohongshu_page.html 页面标题: 健身美女 - 小红书 页面URL: https://www.xiaohongshu.com/search_result?keyword=健身美女 HTML 大小: 245,678 字符 ================================================================================ 🎉 任务完成! ================================================================================ 📁 生成的文件: 1. xhs.json - 搜索结果数据 2. xiaohongshu_page.html - 完整页面HTML ================================================================================ 📌 清理浏览器会话... ✅ 浏览器会话已保存(登录状态已保留) 💡 提示: 下次运行将自动使用保存的登录状态 ``` ### 3. 第二次运行(自动登录) 第二次运行时,由于使用了持久化配置 `xiaohongshu_profile`,浏览器会自动加载之前保存的登录状态: ``` 📌 步骤 3: 检查登录状态... ✅ 已经登录或不需要登录 [直接跳过登录步骤,继续执行任务] ``` --- ## 📁 生成的文件 ### 1. xhs.json - 搜索结果数据 ```json { "success": true, "count": 15, "keyword": "健身美女", "timestamp": "2026-01-29T10:30:45.123Z", "results": [ { "index": 1, "title": "健身美女的日常训练", "author": "小红书用户", "likes": "1.2万", "link": "https://www.xiaohongshu.com/explore/...", "image": "https://..." }, { "index": 2, "title": "健身房打卡", "author": "健身达人", "likes": "8956", "link": "https://www.xiaohongshu.com/explore/...", "image": "https://..." } // ... 更多结果 ] } ``` ### 2. xiaohongshu_page.html - 完整页面 HTML 包含完整的搜索结果页面 HTML,可以在浏览器中打开查看。 文件开头包含元信息: ```html ``` --- ## 🔧 自定义修改 ### 修改搜索关键词 在 `example.py` 中找到这一行: ```python search_keyword = "健身美女" ``` 修改为你想要搜索的关键词: ```python search_keyword = "美食推荐" # 或 search_keyword = "旅游攻略" ``` ### 修改提取的结果数量 在 JavaScript 代码中找到: ```javascript noteCards.forEach((card, index) => { if (index >= 20) return; // 只提取前20个 ``` 修改为你想要的数量: ```javascript if (index >= 50) return; // 提取前50个 ``` ### 修改保存的文件名 ```python # 修改 JSON 文件名 json_file = project_root / "my_search_results.json" # 修改 HTML 文件名 html_file = project_root / "my_page.html" ``` ### 修改滚动页数(加载更多内容) ```python # 滚动页面加载更多内容 await scroll_page(down=True, pages=2.0) # 修改这里的数字 ``` --- ## 🎯 核心技术点 ### 1. 持久化登录状态 ```python await init_browser_session( headless=False, profile_name="xiaohongshu_profile" # 关键! ) ``` 使用专门的 `profile_name`,浏览器会自动保存: - ✅ 登录 Cookie - ✅ LocalStorage - ✅ SessionStorage - ✅ 浏览器缓存 ### 2. 智能登录检测 ```python html_result = await get_page_html() html = html_result.metadata.get('html', '') if "登录" in html or "login" in html.lower(): # 需要登录 await wait_for_user_action("请登录", timeout=300) ``` ### 3. JavaScript 数据提取 ```python extract_js = """ (function(){ // 提取页面数据的 JavaScript 代码 const results = []; // ... 提取逻辑 return { success: true, results: results }; })() """ result = await evaluate(code=extract_js) ``` ### 4. 错误处理 ```python try: # 执行任务 await xiaohongshu_search_task() except Exception as e: print(f"❌ 任务执行失败: {str(e)}") finally: # 确保清理 await cleanup_browser_session() ``` --- ## 🐛 常见问题 ### Q1: 提取不到数据怎么办? **原因**:小红书的页面结构可能变化,导致 CSS 选择器失效。 **解决方案**: 1. 打开生成的 `xiaohongshu_page.html` 文件 2. 查看实际的 HTML 结构 3. 修改 `extract_js` 中的选择器 ```javascript // 修改这些选择器 const noteCards = document.querySelectorAll('你的新选择器'); const titleEl = card.querySelector('你的标题选择器'); ``` ### Q2: 登录后还是提示需要登录? **原因**:登录检测逻辑可能不准确。 **解决方案**: 1. 修改登录检测条件 2. 或者直接跳过登录检测 ```python # 方式1: 修改检测条件 if "请先登录" in html: # 更精确的检测 # 方式2: 手动控制 need_login = False # 如果已经登录,设为 False if need_login: await wait_for_user_action("请登录") ``` ### Q3: 浏览器没有自动保存登录状态? **原因**:可能没有正确调用 `cleanup_browser_session()`。 **解决方案**: 确保在 `finally` 块中调用清理函数: ```python try: # 任务代码 pass finally: await cleanup_browser_session() # 必须调用! ``` ### Q4: 想要提取更多字段怎么办? **解决方案**: 在 `extract_js` 中添加更多提取逻辑: ```javascript results.push({ index: index + 1, title: title, author: author, likes: likes, link: link, image: image, // 添加新字段 description: card.querySelector('.desc')?.textContent || '', tags: Array.from(card.querySelectorAll('.tag')).map(t => t.textContent), publishTime: card.querySelector('.time')?.textContent || '' }); ``` --- ## 🔄 扩展示例 ### 示例 1: 搜索多个关键词 ```python async def search_multiple_keywords(): """搜索多个关键词""" keywords = ["健身美女", "健身教程", "健身饮食"] await init_browser_session(profile_name="xiaohongshu_profile") try: for keyword in keywords: print(f"\n🔍 搜索: {keyword}") # 搜索 search_url = f"https://www.xiaohongshu.com/search_result?keyword={keyword}" await navigate_to_url(search_url) await wait(seconds=5) # 提取数据 # ... (使用相同的提取逻辑) # 保存到不同的文件 json_file = f"xhs_{keyword}.json" # ... 保存 finally: await cleanup_browser_session() ``` ### 示例 2: 点击进入详情页 ```python async def click_and_extract_detail(): """点击笔记进入详情页""" # ... 搜索逻辑 # 获取元素映射 selector_result = await get_selector_map() print(selector_result.output) # 点击第一个笔记(假设索引为 5) await click_element(index=5) await wait(seconds=3) # 提取详情页数据 detail_html = await get_page_html() # ... 保存详情页数据 ``` ### 示例 3: 滚动加载更多 ```python async def load_more_results(): """滚动加载更多结果""" # ... 搜索逻辑 # 多次滚动 for i in range(5): print(f"📜 第 {i+1} 次滚动...") await scroll_page(down=True, pages=2.0) await wait(seconds=2) # 提取所有数据 # ... ``` --- ## 📚 相关文档 - `tools/baseClassTools.py` - 核心工具实现 - `tools/baseClassTools_README.md` - 详细使用文档 - `tools/baseClassTools_examples.py` - 更多示例 - `tools/迁移指南.md` - 从旧工具迁移指南 --- ## 💡 提示 1. **首次运行**:需要手动登录,之后会自动保存登录状态 2. **登录状态**:保存在 `~/.browser_use/profiles/xiaohongshu_profile/` 目录 3. **清除登录**:删除上述目录即可清除登录状态 4. **调试技巧**:查看生成的 HTML 文件了解页面结构 5. **性能优化**:减少 `wait()` 时间可以加快执行速度 --- ## 🎉 开始使用 ```bash # 运行示例 python example.py # 查看生成的文件 ls -lh xhs.json xiaohongshu_page.html # 查看 JSON 数据 cat xhs.json | python -m json.tool # 在浏览器中打开 HTML open xiaohongshu_page.html # macOS # 或 xdg-open xiaohongshu_page.html # Linux # 或 start xiaohongshu_page.html # Windows ``` 祝您使用愉快!🚀