小红书关键词爬虫代码
时间: 2025-06-16 07:24:11 浏览: 21
### 小红书关键词爬虫 Python 代码示例
以下是一个基于 `Playwright` 的小红书关键词爬虫的 Python 代码示例。此代码通过注入 JavaScript 来获取加密参数,从而实现对小红书关键词搜索结果的爬取[^2]。
```python
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as playwright:
# 启动无头浏览器
browser = await playwright.chromium.launch(headless=True)
page = await browser.new_page()
# 添加 stealth.min.js 脚本以绕过反爬机制
await page.add_init_script(path="stealth.min.js")
# 打开小红书搜索页面
url = "https://www.xiaohongshu.com/search"
await page.goto(url)
# 输入关键词并提交搜索
keyword = "Python爬虫"
await page.fill('input[placeholder="搜索你感兴趣的内容"]', keyword)
await page.press('input[placeholder="搜索你感兴趣的内容"]', 'Enter')
# 等待搜索结果加载完成
await page.wait_for_selector('.search-feed-item')
# 提取搜索结果
results = await page.evaluate('''() => {
const items = Array.from(document.querySelectorAll('.search-feed-item'));
return items.map(item => item.innerText);
}''')
# 输出搜索结果
for i, result in enumerate(results, start=1):
print(f"{i}. {result}")
# 关闭浏览器
await browser.close()
# 运行主函数
asyncio.run(main())
```
#### 代码说明
- 使用 `Playwright` 模拟浏览器行为,避免被小红书的反爬机制检测到。
- 通过 `stealth.min.js` 脚本伪装成真实用户,降低被封禁的风险。
- 搜索关键词后,提取 `.search-feed-item` 类下的内容作为搜索结果[^2]。
### 注意事项
- 在实际使用中,需要确保 `stealth.min.js` 文件路径正确,并且文件内容为最新的反爬规避脚本。
- 小红书的页面结构可能会随时间变化,因此需要定期检查和更新选择器 `.search-feed-item`。
- 遵守小红书的《服务条款》和《隐私政策》,避免过度爬取或滥用数据。
阅读全文
相关推荐


















