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

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

爬取步骤

  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
from time import sleep
import json

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

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

# 点击“全部”按钮,展开全部影评
all_btn = driver.find_element_by_xpath('//*[@id="comments-section"]/div[1]/h2/span/a')
all_btn.click()
sleep(2)

# 抓取第一页评论信息
comments = []
for i in range(1, 21):
    name_xpath = f'//*[@id="comments"]/div[{i}]/div[2]/h3/span[2]/a'
    time_xpath = f'//*[@id="comments"]/div[{i}]/div[2]/h3/span[2]/span[3]'
    content_xpath = f'//*[@id="comments"]/div[{i}]/div[2]/p/span/text()'
    name = driver.find_element_by_xpath(name_xpath).text
    time = driver.find_element_by_xpath(time_xpath).text
    content = driver.find_element_by_xpath(content_xpath).text
    comment = {'name': name, 'time': time, 'content': content}
    comments.append(comment)

# 抓取 2-3 页的评论信息
for j in range(1, 3):
    next_page = driver.find_element_by_xpath('//*[@id="paginator"]/a[3]')
    next_page.click()
    sleep(2)
    for i in range(1, 21):
        name_xpath = f'//*[@id="comments"]/div[{i}]/div[2]/h3/span[2]/a'
        time_xpath = f'//*[@id="comments"]/div[{i}]/div[2]/h3/span[2]/span[3]'
        content_xpath = f'//*[@id="comments"]/div[{i}]/div[2]/p/span/text()'
        name = driver.find_element_by_xpath(name_xpath).text
        time = driver.find_element_by_xpath(time_xpath).text
        content = driver.find_element_by_xpath(content_xpath).text
        comment = {'name': name, 'time': time, 'content': content}
        comments.append(comment)

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

driver.quit()

运行结果

image-20210927152805992

注:只展示了部分数据。

总结

本教程详细介绍了如何使用 Python 爬取豆瓣电影《穿靴子的猫2》的影评数据,并以 JSON 格式存储。希望本教程可以帮助你更好地理解网络爬虫技术。


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

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