爬取京东评论数据采用selenium库
爬取代码如下:
# -*- coding: utf-8 -*-
from selenium import webdriver
import json
import time
# 数据写入文本
def write_to_file(content, filepath):
with open(filepath, 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
# 根据search_key关键字爬取数据
def search_key(url):
# 开启浏览器
browser = webdriver.Chrome()
try:
# 获取京东首页
browser.get(url)
button = browser.find_element_by_xpath(
"//li[@clstag='shangpin|keycount|product|shangpinpingjia_1']") # 获取商品评论按钮
button.click() # 控制按钮进行点击
time.sleep(5