python爬虫小红书笔记评论
时间: 2025-04-16 14:44:44 浏览: 47
### 使用 Python 编写爬虫抓取小红书笔记及其评论
#### 工具准备
为了实现这一目标,通常会用到 `requests` 或者更高级的工具如 `scrapy` 来发送 HTTP 请求,并利用 `BeautifulSoup` 或 `lxml` 解析 HTML 文档。对于动态加载的内容,则可能需要用到 Selenium 这样的浏览器自动化框架[^1]。
#### 数据采集过程
当涉及到像小红书这样的社交平台时,由于其页面内容大多由 JavaScript 动态渲染生成,因此直接解析静态网页源码往往无法获得所需的数据。此时可以考虑逆向工程 API 接口调用来获取原始 JSON 响应中的数据[^3]。
```python
import requests
def fetch_notes(keyword, page=1):
url = "https://www.xiaohongshu.com/fe_api/burdock/v2/search/notes"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
# 更多必要的请求头字段...
}
params = {'keyword': keyword, 'page': str(page)}
response = requests.get(url=url, headers=headers, params=params)
data = response.json()
notes = []
for item in data['data']['items']:
note_id = item['id']
title = item['title']
user_name = item['user']['nickname']
comments_url = f"https://www.xiaohongshu.com/api/sns/web/v1/comment/list?note_id={note_id}&cursor="
comment_response = requests.get(comments_url, headers=headers).json()
comments = [{'content': cmt['content'], 'author': cmt['user']['nickname']}
for cmt in comment_response['data']['comments']]
notes.append({
'id': note_id,
'title': title,
'username': user_name,
'comments': comments
})
return notes
```
这段代码展示了如何构建一个简单的函数来查询特定关键词下的笔记以及每条笔记的部分评论信息。需要注意的是,在实际应用中还需要处理分页、异常情况等问题[^2]。
#### 法律风险提示
值得注意的是,未经许可的大规模数据收集行为可能会违反服务条款甚至触犯法律。所以在开展此类活动之前应当仔细阅读网站的服务协议并咨询法律顾问的意见。
阅读全文
相关推荐

















