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

本项目使用Python语言,结合Selenium和BeautifulSoup库,爬取豆瓣电影《穿靴子的猫2》的所有页面的影评数据,包括评论人名称、评论时间和评论内容,并以json格式存储结果。

代码如下:

import time
from selenium import webdriver
from bs4 import BeautifulSoup
import json

# 设置浏览器驱动路径
driver_path = 'C:/chromedriver_win32/chromedriver.exe'
# 创建浏览器对象
browser = webdriver.Chrome(executable_path=driver_path)

# 访问电影的评论页面
url = 'https://movie.douban.com/subject/25868125/comments?status=P'
browser.get(url)

# 点击“全部”按钮,展开全部评论
all_button = browser.find_element_by_xpath('//*[@id="comments-section"]/div[1]/div[2]/a')
all_button.click()
time.sleep(1)

# 获取全部评论页数
soup = BeautifulSoup(browser.page_source, 'html.parser')
page_info = soup.select('.comment-page > a')[-2].get_text()
total_page = int(page_info)

# 循环遍历每一页的评论
comments = []
for i in range(0, total_page):
    # 获取当前页的评论
    url = 'https://movie.douban.com/subject/25868125/comments?start={}&limit=20&status=P&sort=new_score'.format(i*20)
    browser.get(url)
    soup = BeautifulSoup(browser.page_source, 'html.parser')
    comment_list = soup.select('#comments > .comment-item')

    # 解析评论信息
    for comment_item in comment_list:
        comment = {}
        name = comment_item.select('.comment-info > a')[0].get_text().strip()
        time = comment_item.select('.comment-info > span')[0].get_text().strip()
        content = comment_item.select('.short')[0].get_text().strip()
        comment['name'] = name
        comment['time'] = time
        comment['content'] = content
        comments.append(comment)

# 保存评论数据为json文件
with open('comments.json', 'w', encoding='utf-8') as f:
    json.dump(comments, f, ensure_ascii=False)

# 关闭浏览器
browser.quit()

代码说明:

  1. 首先导入必要的库:Selenium、BeautifulSoup、json。
  2. 设置浏览器驱动路径,并创建浏览器对象。
  3. 访问电影的评论页面,并点击“全部”按钮,展开全部评论。
  4. 获取全部评论页数。
  5. 循环遍历每一页的评论,使用BeautifulSoup解析评论信息,并将其存储在列表中。
  6. 将抓取到的数据以文件存储的方式,存储为json格式数据。
  7. 关闭浏览器。

运行结果:

该代码会生成一个名为“comments.json”的json文件,其中包含所有页面的评论数据。

注意事项:

  1. 需要提前安装Selenium、BeautifulSoup、json库。
  2. 需要将代码中的浏览器驱动路径替换为自己的驱动路径。
  3. 由于豆瓣网站的反爬虫机制,可能需要调整代码中的等待时间或代理设置。

总结:

本项目使用Python语言,结合Selenium和BeautifulSoup库,成功爬取了豆瓣电影《穿靴子的猫2》的所有页面的影评数据,并以json格式存储结果。该项目可以帮助用户快速获取和分析电影评论数据,并进行进一步的分析和研究。

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

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

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