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

本教程将使用Python爬虫技术,利用Selenium库和BeautifulSoup库抓取豆瓣电影《穿靴子的猫2》的所有页面的影评数据,并将数据存储为JSON格式文件。

准备工作

  1. 安装必要的库:
pip install selenium beautifulsoup4 requests
  1. 下载Chrome浏览器驱动程序(ChromeDriver),并将其添加到系统环境变量中。

爬取步骤

步骤1: 使用Selenium库点击进入电影全部影评

from selenium import webdriver
import time

url = 'https://movie.douban.com/subject/25868125/'
browser = webdriver.Chrome()
browser.get(url)
time.sleep(2)
all_comment = browser.find_element_by_xpath('//*[@id='comments-section']/div[1]/div[2]/a[2]')
all_comment.click()
time.sleep(2)

步骤2-3: 使用BeautifulSoup库抓取所有页面的评论数据

import requests
from bs4 import BeautifulSoup
import json

url_start = 'https://movie.douban.com/subject/25868125/comments?start='
url_end = '&limit=20&status=P&sort=new_score'
data = []

for i in range(0, 40, 20):
    url = url_start + str(i) + url_end
    html = requests.get(url).text
    soup = BeautifulSoup(html, 'html.parser')
    comment_list = soup.find_all('div', class_='comment-item')
    for comment in comment_list:
        name = comment.find('span', class_='comment-info').find('a').text
        time = comment.find('span', class_='comment-time')['title']
        content = comment.find('span', class_='short').text.strip()
        data.append({'name': name, 'time': time, 'content': content})
    print('抓取第', i/20+1, '页完成')

步骤4: 将抓取到的数据存储为JSON格式文件

with open('comments.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False)

代码解释

  1. 步骤1 使用Selenium库打开豆瓣电影页面,并点击'全部影评'按钮。
  2. 步骤2-3 使用requests库获取网页源代码,并使用BeautifulSoup库解析网页内容,提取评论人名称、评论时间和评论内容。
  3. 步骤4 使用json库将提取的数据存储为JSON格式文件。

注意

  • 由于豆瓣反爬虫机制,建议使用代理IP或设置爬取间隔,避免被封禁。
  • 代码中使用了time.sleep函数,可以根据网站的响应速度调整等待时间。
  • 可以根据自己的需求调整代码,例如爬取更多页面的评论数据,或提取更多评论信息。

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

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