使用Python爬取豆瓣电影《穿靴子的猫2》所有页面的影评数据

本教程将介绍如何使用Python的Selenium库,抓取豆瓣电影《穿靴子的猫2》的所有页面的影评数据,并以JSON格式保存到文件。

目标网站: https://movie.douban.com/subject/25868125/

数据内容: 评论人名称、评论时间以及评论内容

步骤:

  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

# Step 1: Click the 'All Reviews' button to show all reviews
browser = webdriver.Chrome()
url = 'https://movie.douban.com/subject/25868125/'
browser.get(url)
time.sleep(3)
all_reviews_button = browser.find_element_by_xpath('//div[@class='reviews mod-hd']//a[@class='more-link']')
all_reviews_button.click()
time.sleep(3)

# Step 2-3: Loop through all the review pages and scrape data
reviews_data = []
for i in range(10):  # loop through the first 10 pages
    review_url = f'{url}comments?start={i*20}&limit=20&status=P&sort=new_score'
browser.get(review_url)
    time.sleep(3)
    review_items = browser.find_elements_by_xpath('//div[@class='comment-item']')
    for item in review_items:
        name = item.find_element_by_xpath('.//span[@class='comment-info']//a').text
        date = item.find_element_by_xpath('.//span[@class='comment-time ']')
            .get_attribute('title')
        review = item.find_element_by_xpath('.//span[@class='short']').text
        review_data = {
            'name': name,
            'date': date,
            'review': review
        }
        reviews_data.append(review_data)

# Step 4: Save the data to a JSON file
with open('reviews_data.json', 'w', encoding='utf-8') as f:
    json.dump(reviews_data, f, ensure_ascii=False, indent=4)

代码解析:

  1. 使用Selenium库模拟浏览器行为,点击“全部影评”按钮和翻页操作。
  2. 使用XPath定位元素并抓取数据,包括评论人名称、评论时间和评论内容。
  3. 将抓取到的数据以JSON格式保存到文件。

注意事项:

  • 由于豆瓣网站的反爬机制,我们需要适当地增加sleep时间,以免被封IP。
  • 本代码只抓取了前10页的评论数据,你可以根据需要修改循环次数。
  • 你需要安装Selenium库和ChromeDriver驱动程序,并将其路径配置到代码中。

希望本教程可以帮助你成功爬取豆瓣电影《穿靴子的猫2》的影评数据。


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

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