Python爬虫实战:如何抓取京东商品评论并做情感分析
本文介绍了基于Python的京东商品评论爬取与情感分析全流程。通过requests库抓取京东商品评论API数据,利用SnowNLP进行情感分析,将评论分类为正面、负面和中性。文章详细展示了数据预处理、情感评分、可视化分析(词云、情感分布图)以及自动化监控的实现方法,并提供了优化建议如代理池、模型训练和交互式图表。该方案能帮助商家分析产品口碑、识别潜在问题,并支持自动化舆情监控与提醒。
一、前言
在电商平台,商品评论不仅反映用户满意度,还能洞察产品质量、价格敏感度和潜在问题。对于商家和研究者而言,评论数据分析能够提供:
- 产品口碑监控
- 潜在问题快速识别
- 市场策略优化
京东作为国内大型电商平台,其商品评论量大、结构标准化,非常适合做 爬虫数据抓取 + 情感分析 实战。
本文将用 Python 完整展示:
- 京东商品评论爬取
- 数据清洗与处理
- 情感分析(正面/负面/中性)
- 数据可视化与洞察
- 自动化监控与提醒
二、京东评论抓取原理
京东商品页面包含多个数据源:
- 商品基本信息:价格、销量、库存
- 商品评论:默认通过 API 异步加载,URL 结构如下:
https://club.jd.com/comment/productPageComments.action?productId={商品ID}&score=0&sortType=5&page={页码}&pageSize=10
productId:商品IDscore:评论类型(0=全部,1=好评,2=中评,3=差评)sortType:排序(5=按时间)page:页码pageSize:每页数量
接口返回 JSON 数据,方便解析。
三、Python爬虫抓取评论
1. 所需库
import requests
import pandas as pd
import json
import time
2. 爬虫示例
def fetch_jd_comments(product_id, max_page=5):
all_comments = []
for page in range(0, max_page):
url = f"https://club.jd.com/comment/productPageComments.action"
params = {
"productId": product_id,
"score": 0,
"sortType": 5,
"page": page,
"pageSize": 10
}
headers = {
"User-Agent": "Mozilla/5.0"
}
response = requests.get(url, headers=headers, params=params)
data = response.json()
comments = data.get("comments", [])
for c in comments:
all_comments.append({
"id": c["id"],
"content": c["content"],
"creationTime": c["creationTime"],
"score": c["score"]
})
time.sleep(1) # 避免被封
return pd.DataFrame(all_comments)
df_comments = fetch_jd_comments(product_id="100012043978", max_page=10)
df_comments.to_csv("jd_comments.csv", index=False)
print(df_comments.head())
💡 提示:
- 爬取多页时注意 请求间隔 避免封IP
- 可加入 代理池 提升稳定性
四、评论数据清洗
1. 去重和缺失值处理
df_comments.drop_duplicates(subset="id", inplace=True)
df_comments.dropna(subset=["content"], inplace=True)
2. 文本预处理
- 去掉空格、换行符
- 去除特殊符号
import re
df_comments["clean_content"] = df_comments["content"].apply(lambda x: re.sub(r"[^\w\s]", "", x))
五、评论情感分析
1. 使用 SnowNLP
SnowNLP 是 Python 中文情感分析库,可以对中文文本进行情感评分(0~1,0负面,1正面):
from snownlp import SnowNLP
df_comments["sentiment"] = df_comments["clean_content"].apply(lambda x: SnowNLP(x).sentiments)
2. 情感分类
def classify_sentiment(score):
if score > 0.7:
return "正面"
elif score < 0.3:
return "负面"
else:
return "中性"
df_comments["sentiment_label"] = df_comments["sentiment"].apply(classify_sentiment)
print(df_comments["sentiment_label"].value_counts())
六、可视化与洞察
1. 情感分布图
import matplotlib.pyplot as plt
df_comments["sentiment_label"].value_counts().plot(kind="bar", color=["green", "red", "gray"])
plt.title("京东商品评论情感分布")
plt.ylabel("评论数量")
plt.show()
2. 时间序列分析
df_comments["creationTime"] = pd.to_datetime(df_comments["creationTime"])
time_sentiment = df_comments.groupby([df_comments["creationTime"].dt.date, "sentiment_label"]).size().unstack().fillna(0)
time_sentiment.plot(figsize=(12,6))
plt.title("评论情感随时间变化")
plt.xlabel("日期")
plt.ylabel("评论数量")
plt.show()
七、热门关键词分析
1. 分词处理
使用 jieba 分词:
import jieba
from collections import Counter
all_words = []
for content in df_comments["clean_content"]:
all_words.extend(jieba.lcut(content))
# 去掉停用词
stopwords = set(["的", "了", "和", "是"])
all_words = [w for w in all_words if w not in stopwords and len(w)>1]
word_counts = Counter(all_words)
print(word_counts.most_common(20))
2. 词云可视化
from wordcloud import WordCloud
wc = WordCloud(font_path="simsun.ttf", width=800, height=400, background_color="white")
wc.generate_from_frequencies(word_counts)
plt.figure(figsize=(12,6))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
八、自动化监控与提醒
1. 定时爬取
使用 APScheduler 定时任务,每天抓取最新评论:
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('cron', hour=0)
def scheduled_fetch():
df = fetch_jd_comments(product_id="100012043978", max_page=5)
# 数据清洗 + 情感分析
df.to_csv("jd_comments_daily.csv", index=False)
sched.start()
2. 异常评论提醒
可统计负面评论比例,超过阈值发送邮件或微信提醒:
negative_ratio = (df_comments["sentiment_label"]=="负面").mean()
if negative_ratio > 0.3:
send_email(subject="负面评论异常提醒", content=f"负面评论占比 {negative_ratio:.2%}", to_email="xxx@example.com")
九、工程化与优化建议
-
高频爬取
- 使用多线程或异步抓取
- 配合代理池避免封 IP
-
数据存储优化
- SQLite 适合个人分析
- MySQL/PostgreSQL 适合大规模评论数据
-
情感分析优化
- SnowNLP 可快速使用
- 对特定领域可训练专用模型(BERT、LSTM)提高准确率
-
可视化优化
- Plotly/Dash 构建交互式图表
- 提供网页/移动端监控
-
选品与舆情监控
- 结合评论情感 + 销量趋势进行选品决策
- 对竞争产品进行对比分析
十、总结
本文完整演示了 Python爬虫抓取京东商品评论 + 中文情感分析 + 可视化洞察 的实战流程:
- 数据采集:requests + JSON API + Selenium
- 数据清洗:去重、文本预处理
- 情感分析:SnowNLP + 分类标签
- 可视化洞察:柱状图、时间序列、词云
- 自动化监控:定时任务 + 异常提醒
通过该系统,商家或分析师可以实现 每日评论更新 + 情感监控 + 关键问题发现,为产品优化、客户服务和选品策略提供数据支撑。
未来扩展方向:
- 使用深度学习模型(BERT、RoBERTa)提升情感分析准确率
- 构建交互式监控平台(Dash/Streamlit)
- 自动分析竞争对手舆情
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)