使用Python爬取豆瓣电影《穿靴子的猫2》影评数据 - 代码示例

本文将使用Python和Selenium库,抓取豆瓣电影《穿靴子的猫2》的所有页面影评数据,包括评论人名称、评论时间和评论内容。

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

步骤:

1. 借助Selenium库,点击进入电影全部影评

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 设置Chrome浏览器的可执行文件路径
executable_path = 'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe'

# 创建一个Chrome浏览器对象
browser = webdriver.Chrome(executable_path=executable_path)

# 打开豆瓣电影《穿靴子的猫2》的页面
url = 'https://movie.douban.com/subject/25868125/'
browser.get(url)

# 点击“全部影评”按钮
element = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.LINK_TEXT, '全部影评')))
element.click()

2. 从'https://movie.douban.com/subject/25868125/comments?start=0&limit=20&status=P&sort=new_score'地址开始,抓取第一页的评论人名称、评论时间以及评论。

import time

# 定义一个函数,用于抓取一页的影评数据
def get_comments_from_one_page(start):
    # 构造评论页面的URL
    url = f'https://movie.douban.com/subject/25868125/comments?start={start}&limit=20&status=P&sort=new_score'
    browser.get(url)
    time.sleep(2)
    
    # 获取所有的评论区块
    comments = browser.find_elements_by_css_selector('.comment-item')
    
    # 遍历每个评论区块,提取评论人名称、评论时间以及评论
    for comment in comments:
        name = comment.find_element_by_css_selector('.comment-info a').text
        time = comment.find_element_by_css_selector('.comment-info .comment-time').text
        content = comment.find_element_by_css_selector('.comment p').text
        
        print(f'评论人:{name},评论时间:{time},评论内容:{content}
')

# 抓取第一页的影评数据
get_comments_from_one_page(0)

3. 继续抓取2-3页的所有评论人名称、评论时间以及评论。

# 抓取第二页和第三页的影评数据
get_comments_from_one_page(20)
get_comments_from_one_page(40)

# 关闭浏览器
browser.quit()

注意:

  • 请确保你已经安装了Selenium库。
  • 请将代码中的executable_path变量替换为你的Chrome浏览器驱动程序的路径。
  • 该代码示例仅演示了抓取前三页评论数据,你可以根据需要修改代码,抓取更多页面数据。

希望本文能够帮助你学习网络爬虫技术!


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

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