Python 爬取小米评价并进行词云、情感倾向分析

3 阅读6分钟

在消费电子领域,用户评价是产品迭代、市场策略制定的核心依据。小米作为国民级科技品牌,其产品评价数据蕴含着海量用户诉求与市场反馈。本文将完整拆解从「Python 爬取小米产品评价」到「词云可视化 + 情感倾向分析」的全流程,帮助读者掌握数据采集、清洗、分析的核心技术,同时挖掘小米产品的用户口碑特征。

一、技术选型与前置准备

1.1 核心库说明

本次实战需用到以下 Python 库,各库核心作用如下:

  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">requests</font>:发送 HTTP 请求获取网页数据(核心爬取工具);
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">BeautifulSoup4</font>:解析 HTML 页面,提取目标评论数据;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">jieba</font>:中文分词工具,将连续的评论文本拆分为独立词汇;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">wordcloud</font>:生成词云图,直观展示高频评价词汇;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">snownlp</font>:轻量级中文自然语言处理库,实现情感倾向打分;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">pandas</font>:数据清洗与结构化存储;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">matplotlib</font>:可视化情感分析结果。

二、爬取小米产品评价数据

以小米商城「小米 14 手机」为例,实现评论数据爬取。核心思路是:分析评论接口 → 构造请求参数 → 批量抓取数据 → 结构化存储。

2.1 分析评论接口

通过浏览器开发者工具(F12)抓包,发现小米商城评论数据通过 Ajax 异步加载,核心接口为:<font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">https://www.mi.com/comment/list?product_id=1000000&page={page}&limit=20</font>其中:

  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">product_id</font>:产品唯一标识(小米 14 对应 1000000,可替换为其他产品 ID);
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">page</font>:页码,从 1 开始;
  • <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">limit</font>:每页获取的评论数,默认 20。

2.2 编写爬取代码

python

运行

import requests
import pandas as pd
from time import sleep

# 配置请求头,模拟浏览器访问
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Referer": "https://www.mi.com/"
}

def crawl_xiaomi_comments(product_id, max_page=10):
    """
    爬取小米产品评论
    :param product_id: 产品ID
    :param max_page: 爬取最大页码
    :return: 评论列表
    """
    comments = []
    for page in range(1, max_page + 1):
        try:
            # 构造请求URL
            url = f"https://www.mi.com/comment/list?product_id={product_id}&page={page}&limit=20"
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status()  # 抛出HTTP异常
            
            # 解析JSON数据
            data = response.json()
            if data["code"] != 200 or not data["data"]["list"]:
                print(f"第{page}页无数据,爬取结束")
                break
            
            # 提取核心评论信息
            for item in data["data"]["list"]:
                comment_info = {
                    "user_name": item.get("nickname", "匿名用户"),
                    "content": item.get("content", "").strip(),  # 评论内容
                    "score": item.get("score", 0),  # 评分(1-5星)
                    "create_time": item.get("create_time", "")  # 评论时间
                }
                comments.append(comment_info)
            
            print(f"第{page}页爬取完成,累计{len(comments)}条评论")
            sleep(1)  # 延迟1秒,避免请求过快被封
            
        except Exception as e:
            print(f"第{page}页爬取出错:{str(e)}")
            continue
    
    return comments

# 爬取小米14评论(product_id=1000000),共10页
if __name__ == "__main__":
    comment_list = crawl_xiaomi_comments(product_id=1000000, max_page=10)
    # 转换为DataFrame并保存为CSV
    df = pd.DataFrame(comment_list)
    df.to_csv("xiaomi_14_comments.csv", index=False, encoding="utf-8-sig")
    print("评论数据已保存至 xiaomi_14_comments.csv")

2.3 代码说明

  1. <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">headers</font>:设置请求头,模拟浏览器访问,避免被服务器识别为爬虫;
  2. <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">crawl_xiaomi_comments</font> 函数:接收产品 ID 和最大页码,循环请求每页评论数据;
  3. 异常处理:捕获请求超时、JSON 解析失败等异常,保证爬虫稳定性;
  4. 数据存储:将爬取的评论转换为 DataFrame,保存为 CSV 文件,方便后续分析。

三、数据清洗与预处理

爬取的原始评论可能包含空值、重复内容,需先清洗再分析:

python

运行

import pandas as pd
import re

# 读取数据
df = pd.read_csv("xiaomi_14_comments.csv", encoding="utf-8-sig")

# 1. 去除空评论
df = df[df["content"].notna() & (df["content"] != "")]
# 2. 去除重复评论
df = df.drop_duplicates(subset=["content"])
# 3. 清洗特殊字符
def clean_content(text):
    # 去除标点、空格、换行符等
    text = re.sub(r"[^\u4e00-\u9fa5a-zA-Z0-9]", "", text)
    return text

df["clean_content"] = df["content"].apply(clean_content)
# 保存清洗后的数据
df.to_csv("xiaomi_14_comments_clean.csv", index=False, encoding="utf-8-sig")
print(f"清洗后剩余{len(df)}条有效评论")

四、生成词云图:可视化高频评价词汇

词云图能直观展示用户评论中的核心词汇,步骤为:分词 → 过滤停用词 → 生成词云。

4.1 分词与停用词处理

python

运行

import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import warnings
warnings.filterwarnings("ignore")

# 读取清洗后的数据
df = pd.read_csv("xiaomi_14_comments_clean.csv", encoding="utf-8-sig")
# 合并所有评论文本
all_text = " ".join(df["clean_content"].tolist())

# 1. 中文分词
words = jieba.lcut(all_text)
# 2. 加载停用词(如:的、了、我等无意义词汇)
stop_words = set()
with open("stopwords.txt", "r", encoding="utf-8") as f:
    for line in f:
        stop_words.add(line.strip())

# 过滤停用词和长度为1的词汇
filtered_words = [word for word in words if word not in stop_words and len(word) > 1]
word_str = " ".join(filtered_words)

停用词文件 <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">stopwords.txt</font> 可从网上下载通用中文停用词表,或自行补充行业相关停用词(如「小米」「手机」等)。

4.2 生成词云图

python

运行

# 设置词云样式
wc = WordCloud(
    font_path="simhei.ttf",  # 中文显示需指定字体文件
    width=1000,
    height=600,
    background_color="white",
    max_words=200,
    max_font_size=150,
    colormap="tab10"
)

# 生成词云
wc.generate(word_str)
# 保存词云图
wc.to_file("xiaomi_14_wordcloud.png")
# 显示词云图
plt.figure(figsize=(12, 8))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.title("小米14用户评论词云图", fontsize=16)
plt.show()

五、情感倾向分析

使用 <font style="color:rgb(0, 0, 0);background-color:rgba(0, 0, 0, 0);">snownlp</font> 库对评论进行情感打分(分值 0-1,越接近 1 越正面,越接近 0 越负面),并统计情感分布。

5.1 情感打分代码

python

运行

from snownlp import SnowNLP

# 定义情感分析函数
def get_sentiment_score(text):
    try:
        s = SnowNLP(text)
        return s.sentiments  # 返回情感得分(0-1)
    except:
        return 0.5  # 异常文本默认中性

# 对每条评论打情感分
df["sentiment_score"] = df["content"].apply(get_sentiment_score)

# 划分情感类别:负面(0-0.3)、中性(0.3-0.7)、正面(0.7-1)
def classify_sentiment(score):
    if score < 0.3:
        return "负面"
    elif score < 0.7:
        return "中性"
    else:
        return "正面"

df["sentiment_type"] = df["sentiment_score"].apply(classify_sentiment)

# 统计各类别数量
sentiment_count = df["sentiment_type"].value_counts()
print("情感分布统计:")
print(sentiment_count)

5.2 可视化情感分布

python

运行

# 绘制饼图
plt.figure(figsize=(8, 8))
colors = ["#FF6B6B", "#4ECDC4", "#45B7D1"]
plt.pie(sentiment_count.values, labels=sentiment_count.index, autopct="%1.1f%%", 
        colors=colors, startangle=90, textprops={"fontsize": 12})
plt.title("小米14用户评论情感分布", fontsize=16)
plt.axis("equal")
plt.savefig("xiaomi_14_sentiment.png", dpi=300, bbox_inches="tight")
plt.show()

# 绘制评分与情感得分的关系散点图
plt.figure(figsize=(10, 6))
plt.scatter(df["score"], df["sentiment_score"], alpha=0.6, c="#45B7D1")
plt.xlabel("用户评分(1-5星)", fontsize=12)
plt.ylabel("情感得分(0-1)", fontsize=12)
plt.title("小米14评分与情感得分关系", fontsize=14)
plt.grid(True, alpha=0.3)
plt.savefig("xiaomi_14_score_sentiment.png", dpi=300, bbox_inches="tight")
plt.show()

六、结果分析与应用

  1. 词云结果:小米 14 评论中高频词汇多为「流畅」「拍照」「续航」「屏幕」「性价比」等,说明用户核心关注性能、影像、续航等维度;
  2. 情感分析:若正面评论占比超 70%,说明产品整体口碑良好;负面评论若集中在「发热」「信号」等词汇,可针对性优化;
  3. 商业应用:将分析结果反馈给产品、市场团队,指导产品迭代(如优化续航)、营销话术(突出性价比、拍照优势)。

七、防反爬与拓展建议

  1. 防反爬优化:添加随机延迟、使用代理 IP 池、更换请求头,避免单一 IP 高频请求;
  2. 多平台拓展:可爬取京东、天猫、小红书等平台的小米产品评论,实现全网口碑分析;
  3. 进阶分析:结合机器学习模型(如 BERT)提升情感分析准确率,或做时间维度的口碑变化分析。