京东商品评论(2)
import time
import csv
#导入自动化模块
from DrissionPage import ChromiumPage
#创建文件对象
f = open('data.csv', mode='w', encoding='utf-8', newline='')
#字典写入方法
csv.DictWriter(f, fieldnames=['昵称','评论','评分','产品','日期',
])
#写入表头
csv_writer.writeheader()
#打开浏览器
dp = ChromiumPage()
#访问网站
dp.get('https://item.jd.com/10089562735488.html')
time.sleep(2)
#监听数据
dp.listen.start('client.action')
#点击加载全部评论
dp.ele('css:.all-btn .arrow').click(by_js=True)
#等待数据包加载
r = dp.listen.wait()
#获取响应数据
json_data = r.response.body
print(json_data)
#字典取值,提取评论信息所在的列表
comment_list = json_data['result']['floors'][2]['data']
#print(comment_list)
#for 循环遍历,提取列表里的元素
for index in comment_list:#提取每条评论信息if 'commentInfo' in [i for i in index.keys()]:#异常捕获:判断‘commentInfo’键是否存在dit = {'昵称':index['commentInfo']['userNickName'],'评论':index['commentInfo']['commentData'],'评分':index['commentInfo']['commentScore'],'产品':index['commentInfo']['productSpecifications'].replace('已购', ''),'日期':index['commentInfo']['commentDate']}#写入数据csv_writer.writerow(dit)print(dit)else:pass
商品评论获取
异常捕获