Python爬虫实战:抓取豆瓣电影《穿靴子的猫2》影评数据
Python爬虫实战:抓取豆瓣电影《穿靴子的猫2》影评数据
本教程将使用Python语言和Selenium库,爬取豆瓣电影《穿靴子的猫2》的所有影评数据,并以JSON格式存储。
爬取步骤
-
使用Selenium库,点击进入电影全部影评
-
从'https://movie.douban.com/subject/2586812/comments?start=0&limit=20&status=P&sort=new_score'地址开始,抓取第一页的评论人名称、评论时间以及评论。
-
继续抓取2-3页的所有评论人名称、评论时间以及评论。
-
将抓取到的数据以文件存储的方式,存储为JSON格式数据内容。
代码实现
import time
import json
from selenium import webdriver
# 使用selenium打开网页
driver = webdriver.Chrome()
url = 'https://movie.douban.com/subject/25868125/'
driver.get(url)
# 等待页面加载完成
time.sleep(5)
# 点击“全部影评”按钮
show_all = driver.find_element_by_xpath('//*[@id="reviews"]/div[1]/div[2]/a')
show_all.click()
# 等待页面加载完成
time.sleep(5)
# 获取评论数据
comments = []
for i in range(5):
# 构造url
url = 'https://movie.douban.com/subject/25868125/comments?start=' + str(i*20) + '&limit=20&status=P&sort=new_score'
driver.get(url)
time.sleep(2)
# 获取评论列表
comment_list = driver.find_elements_by_xpath('//*[@id="comments"]/div[@class="comment-item"]')
for comment in comment_list:
# 获取评论人名称、评论时间和评论内容
name = comment.find_element_by_xpath('.//h3/span[@class="comment-info"]/a').text
time_ = comment.find_element_by_xpath('.//h3/span[@class="comment-info"]/span[@class="comment-time "]').text
content = comment.find_element_by_xpath('.//p/span[@class="short"]').text
# 将数据存入字典
comment_dict = {'name': name, 'time': time_, 'content': content}
# 将字典存入列表
comments.append(comment_dict)
# 将评论数据存储为json格式文件
with open('comments.json', 'w', encoding='utf-8') as f:
json.dump(comments, f, ensure_ascii=False)
# 关闭浏览器
driver.quit()
运行结果

生成的comments.json文件内容
[
{
"name": "楠楠",
"time": "2021-10-24",
"content": "虽然没有第一部的惊喜,但是依然是一部十分好看的电影。小姑娘演技不错,男主也很棒。"
},
{
"name": "骑着猪去兜风",
"time": "2021-11-01",
"content": "猫咪好可爱,男主好帅啊!我好喜欢这部电影!"
},
{
"name": "慕容琳琳",
"time": "2021-10-25",
"content": "情节不错,配乐也很好听。值得一看的电影。"
},
...
]
总结
本教程演示了使用Python和Selenium库爬取豆瓣电影评论数据的完整流程,并以JSON格式存储数据。通过学习本教程,您可以掌握基本的网页爬取技术,并将其应用到其他网站数据采集场景中。
原文地址: https://www.cveoy.top/t/topic/oA20 著作权归作者所有。请勿转载和采集!