example.py 是一个完整的小红书搜索示例,展示了如何使用 baseClassTools.py 实现实际的自动化任务。
xhs.json 文件xiaohongshu_page.html 文件# 在项目根目录下运行
python example.py
🚀 开始执行小红书搜索任务
================================================================================
📌 步骤 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
================================================================================
📌 清理浏览器会话...
✅ 浏览器会话已保存(登录状态已保留)
💡 提示: 下次运行将自动使用保存的登录状态
第二次运行时,由于使用了持久化配置 xiaohongshu_profile,浏览器会自动加载之前保存的登录状态:
📌 步骤 3: 检查登录状态...
✅ 已经登录或不需要登录
[直接跳过登录步骤,继续执行任务]
{
"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://..."
}
// ... 更多结果
]
}
包含完整的搜索结果页面 HTML,可以在浏览器中打开查看。
文件开头包含元信息:
<!--
页面标题: 健身美女 - 小红书
页面URL: https://www.xiaohongshu.com/search_result?keyword=健身美女
保存时间: 2026-01-29 10:30:45
搜索关键词: 健身美女
-->
在 example.py 中找到这一行:
search_keyword = "健身美女"
修改为你想要搜索的关键词:
search_keyword = "美食推荐"
# 或
search_keyword = "旅游攻略"
在 JavaScript 代码中找到:
noteCards.forEach((card, index) => {
if (index >= 20) return; // 只提取前20个
修改为你想要的数量:
if (index >= 50) return; // 提取前50个
# 修改 JSON 文件名
json_file = project_root / "my_search_results.json"
# 修改 HTML 文件名
html_file = project_root / "my_page.html"
# 滚动页面加载更多内容
await scroll_page(down=True, pages=2.0) # 修改这里的数字
await init_browser_session(
headless=False,
profile_name="xiaohongshu_profile" # 关键!
)
使用专门的 profile_name,浏览器会自动保存:
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)
extract_js = """
(function(){
// 提取页面数据的 JavaScript 代码
const results = [];
// ... 提取逻辑
return { success: true, results: results };
})()
"""
result = await evaluate(code=extract_js)
try:
# 执行任务
await xiaohongshu_search_task()
except Exception as e:
print(f"❌ 任务执行失败: {str(e)}")
finally:
# 确保清理
await cleanup_browser_session()
原因:小红书的页面结构可能变化,导致 CSS 选择器失效。
解决方案:
xiaohongshu_page.html 文件extract_js 中的选择器// 修改这些选择器
const noteCards = document.querySelectorAll('你的新选择器');
const titleEl = card.querySelector('你的标题选择器');
原因:登录检测逻辑可能不准确。
解决方案:
# 方式1: 修改检测条件
if "请先登录" in html: # 更精确的检测
# 方式2: 手动控制
need_login = False # 如果已经登录,设为 False
if need_login:
await wait_for_user_action("请登录")
原因:可能没有正确调用 cleanup_browser_session()。
解决方案:
确保在 finally 块中调用清理函数:
try:
# 任务代码
pass
finally:
await cleanup_browser_session() # 必须调用!
解决方案:
在 extract_js 中添加更多提取逻辑:
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 || ''
});
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()
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()
# ... 保存详情页数据
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 - 从旧工具迁移指南~/.browser_use/profiles/xiaohongshu_profile/ 目录wait() 时间可以加快执行速度# 运行示例
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
祝您使用愉快!🚀