jupyter爬取评论
时间: 2025-01-15 08:44:52 浏览: 36
### 如何在 Jupyter Notebook 中编写爬虫程序来抓取网页评论
#### 环境配置
为了能够在 Jupyter Notebook 中顺利运行 Python 代码并实现网页评论的抓取,需先安装必要的库。通常情况下,`requests` 库用于发送 HTTP 请求;而 `BeautifulSoup` 或者 `lxml` 则用来解析 HTML 文档。
```bash
pip install requests beautifulsoup4 lxml
```
确保这些依赖项已经成功安装到当前使用的 Python 环境中[^1]。
#### 网页分析
选取目标网站后,打开开发者工具 (F12),查看页面加载过程中发出的各种请求及其对应的 URL 和参数设置。对于动态加载的内容,可能还需要借助 Selenium 这样的自动化测试框架模拟浏览器行为以获取完整的 DOM 结构[^3]。
#### 编写爬虫脚本
下面是一个简单的例子展示怎样利用上述提到的技术栈在一个新的单元格里构建基本功能:
```python
import requests
from bs4 import BeautifulSoup
def fetch_comments(url, headers=None):
"""Fetch comments from a given webpage."""
try:
resp = requests.get(url=url, headers=headers)
if resp.status_code != 200:
raise Exception(f"Failed to load page {url}")
soup = BeautifulSoup(resp.content, "html.parser")
# 假设评论位于 class="comment-item" 的 div 下面
comment_divs = soup.find_all('div', {'class': 'comment-item'})
results = []
for item in comment_divs:
author = item.select_one('.author').text.strip()
content = item.select_one('.content p').text.strip()
result_dict = {
'Author': author,
'Content': content
}
results.append(result_dict)
return results
except Exception as e:
print(e)
return None
```
这段代码定义了一个名为 `fetch_comments()` 函数,接受两个参数:一个是待访问的目标网址 (`url`) ,另一个可选的是自定义头部信息(`headers`) 。函数内部实现了异常处理机制以及对返回结果进行了初步的数据清洗工作[^4]。
#### 数据保存
当完成数据收集之后,可以考虑将其导出至本地文件系统以便后续处理或分享给他人查阅。这里提供了一种简单的方式——将列表形式的结果转换成 JSON 字符串再存入 `.json` 文件当中。
```python
import json
comments_data = fetch_comments("http://example.com/comments")
if comments_data is not None and isinstance(comments_data, list):
with open("./output/comments.json", mode='w+', encoding='utf-8') as file_obj:
json.dump(obj=comments_data, fp=file_obj, ensure_ascii=False, indent=4)
```
以上就是整个流程的大致介绍,在实际操作时还需针对具体情况进行调整优化[^5]。
阅读全文
相关推荐


















