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

本教程将使用Python的Selenium库和BeautifulSoup库,抓取《穿靴子的猫2》在豆瓣电影上的所有页面的影评数据,并以JSON格式存储结果。

步骤1:使用Selenium进入电影全部影评页面

首先,需要下载Selenium库和chromedriver,安装chromedriver并将其路径添加到环境变量中。

然后,可以使用以下代码进入全部影评页面:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get('https://movie.douban.com/subject/25868125/')
elem = driver.find_element_by_xpath('//*[@id="reviews"]/div[1]/div[2]/a')
elem.click()

步骤2:抓取第一页评论信息

接下来,可以使用以下代码抓取第一页的评论信息:

import requests
from bs4 import BeautifulSoup

url = 'https://movie.douban.com/subject/25868125/comments?start=0&limit=20&status=P&sort=new_score'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
comments = soup.find_all('div', class_='comment-item')

data = []
for comment in comments:
    name = comment.find('span', class_='comment-info').a.get_text()
    time = comment.find('span', class_='comment-time').get_text().strip()
    content = comment.find('span', class_='short').get_text().strip()
    data.append({'name': name, 'time': time, 'content': content})

print(data)

步骤3:抓取2-3页评论信息

接下来,可以使用以下代码抓取2-3页的评论信息:

for i in range(2, 4):
    url = 'https://movie.douban.com/subject/25868125/comments?start=' + str((i-1)*20) + '&limit=20&status=P&sort=new_score'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    comments = soup.find_all('div', class_='comment-item')

    for comment in comments:
        name = comment.find('span', class_='comment-info').a.get_text()
        time = comment.find('span', class_='comment-time').get_text().strip()
        content = comment.find('span', class_='short').get_text().strip()
        data.append({'name': name, 'time': time, 'content': content})

print(data)

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

最后,可以使用以下代码将抓取到的数据存储为JSON格式数据:

import json

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

注意:

  • 上述代码仅抓取了前3页的评论信息,如果需要抓取更多页面的评论信息,需要修改代码中的循环范围。
  • 豆瓣网站的反爬虫机制可能随时更新,需要根据实际情况调整代码。
  • 抓取网站数据时,请遵守网站的 robots.txt 协议,避免对网站造成负面影响。

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

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