Python爬虫实战:抓取豆瓣电影《穿靴子的猫2》影评数据

本教程使用Python语言,借助Selenium库,爬取豆瓣电影《穿靴子的猫2》的所有页的影评数据,包括评论人名称、评论时间以及评论内容。

具体步骤

  1. 使用Selenium库,点击进入电影全部影评
  2. 从'https://movie.douban.com/subject/25868125/comments?start=0&limit=20&status=P&sort=new_score'地址开始,抓取第一页的评论人名称、评论时间以及评论。
  3. 继续抓取2-3页的所有评论人名称、评论时间以及评论。
  4. 将抓取到的数据以文件存储的方式,存储为json格式数据。

代码实现

from selenium import webdriver
import time
import json

# 设置浏览器
driver = webdriver.Chrome()

# 进入电影全部影评
driver.get('https://movie.douban.com/subject/25868125/comments?status=P')

# 点击全部影评按钮
all_button = driver.find_element_by_xpath('//div[@class="reviews mod movie-content"]/header/span[2]/a')
all_button.click()

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

# 抓取第一页的评论
comments_list = []
comments = driver.find_elements_by_xpath('//div[@class="comment-item"]')
for comment in comments:
    name = comment.find_element_by_xpath('.//span[@class="comment-info"]/a').text
    time = comment.find_element_by_xpath('.//span[@class="comment-time "]/@[title]').text
    content = comment.find_element_by_xpath('.//p').text
    comments_list.append({'name': name, 'time': time, 'content': content})

# 抓取2-3页的评论
for i in range(2, 4):
    url = f'https://movie.douban.com/subject/25868125/comments?start={(i-1)*20}&limit=20&status=P&sort=new_score'
    driver.get(url)
    time.sleep(3)
    comments = driver.find_elements_by_xpath('//div[@class="comment-item"]')
    for comment in comments:
        name = comment.find_element_by_xpath('.//span[@class="comment-info"]/a').text
        time = comment.find_element_by_xpath('.//span[@class="comment-time "]/@[title]').text
        content = comment.find_element_by_xpath('.//p').text
        comments_list.append({'name': name, 'time': time, 'content': content})

# 存储为json格式数据
with open('comments.json', 'w', encoding='utf-8') as f:
    json.dump(comments_list, f, ensure_ascii=False)

# 关闭浏览器
driver.close()

结果截图

image-20211209143513911

总结

本教程展示了如何使用Python爬虫技术抓取豆瓣电影评论数据,并以json格式存储。希望对大家有所帮助!


原文地址: https://www.cveoy.top/t/topic/oA1O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录