2020 级课前测试试卷-电子商务大数据分析 爬取京东商品评论数据,基于hadoop实现数据分析以及数据可视化

数据采集:
要求Python 编写程序爬取京东手机评论数据,生成Json形式的数据文件。

点击查看代码
# 导入自动化模块
import time
import json
from datetime import datetime

from DrissionPage import ChromiumPage
from DrissionPage.common import Actions

# 打开浏览器
dp = ChromiumPage()

# 实例化动作链对象
ac = Actions(dp)

# 访问网站
dp.get('https://item.jd.com/10087782648613.html')

# 等待页面加载
time.sleep(3)

# 监听数据
dp.listen.start('client.action')

# 点击加载全部评论
try:
    dp.ele('css:.all-btn .arrow').click()
    time.sleep(2)
except:
    print("无法点击加载全部评论按钮,尝试继续...")

# 存储所有评论数据
all_comments = []

# 添加连续失败计数器
consecutive_failures = 0

# 构建循环
for page in range(1, 2001):
    print(f'正在采集第{page}页的数据')

    # 等待数据包加载,添加超时处理
    try:
        r = dp.listen.wait(timeout=15)  # 设置15秒超时
        if r is None:
            print(f"第{page}页等待数据包超时")
            consecutive_failures += 1
            if consecutive_failures >= 3:
                print("连续3次等待数据包超时,结束采集")
                break
            continue
    except Exception as e:
        print(f"等待第{page}页数据包时出错: {e}")
        consecutive_failures += 1
        if consecutive_failures >= 3:
            print("连续3次等待数据包出错,结束采集")
            break
        continue

    # 获取响应数据
    try:
        json_data = r.response.body
    except Exception as e:
        print(f"获取第{page}页响应数据时出错: {e}")
        consecutive_failures += 1
        if consecutive_failures >= 3:
            print("连续3次获取响应数据出错,结束采集")
            break
        continue

    # 解析数据
    try:
        # 字典取值,提取评论信息所在列表
        comment_list = json_data['result']['floors'][2]['data']

        # for循环遍历,提取列表里面的元素
        for index in comment_list:
            """提取具体每条评论信息"""

            if 'commentInfo' in index:
                # 直接保存完整的commentInfo数据,不做任何处理
                all_comments.append(index['commentInfo'])
                print(f"采集到评论: {index['commentInfo']['userNickName']}")

        # 如果成功解析,重置连续失败计数器
        consecutive_failures = 0

    except Exception as e:
        print(f"解析第{page}页数据时出错: {e}")
        consecutive_failures += 1

        # 检查是否连续失败3次
        if consecutive_failures >= 3:
            print("连续3次解析数据失败,结束采集")
            break
        else:
            continue

    # 定位窗口标签并下滑
    try:
        tab = dp.ele('css:div._rateListContainer_1ygkr_45')
        tab.scroll.to_bottom()
        time.sleep(2)  # 等待加载
    except Exception as e:
        print(f"滚动加载失败: {e}")
        # 滚动失败不视为解析失败,不增加连续失败计数
        continue

# 保存原始数据到JSON文件,每行一个JSON对象
output_filename = f'jd_comments_raw_{datetime.now().strftime("%Y%m%d_%H%M%S")}.json'
try:
    with open(output_filename, 'w', encoding='utf-8') as f:
        for comment in all_comments:
            # 每行写入一个JSON对象
            json.dump(comment, f, ensure_ascii=False)
            f.write('\n')  # 换行
    print(f"原始数据已保存到 {output_filename},共采集 {len(all_comments)} 条评论")
except Exception as e:
    print(f"保存文件时出错: {e}")

# 关闭浏览器
dp.quit()

说明可能问题,报错找不到浏览器,此前可以先运行一遍

from DrissionPage import ChromiumOptions

path = r'D:\Chrome\Chrome.exe'  # 请改为你电脑内Chrome可执行文件路径
ChromiumOptions().set_browser_path(path).save()
posted @ 2025-12-02 08:11  mwhB  阅读(13)  评论(0)    收藏  举报