使用网络爬虫技术,抓取《穿靴子的猫2》在豆瓣电影上的所有页的影评数据,抓取地址:

https://movie.douban.com/subject/25868125/

步骤1:借助Selenium库,点击进入电影全部影评

首先需要安装Selenium库和Chromedriver。

pip install selenium

下载Chromedriver并设置环境变量。

代码如下:

from selenium import webdriver
import time

# 使用Chrome浏览器
browser = webdriver.Chrome()

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

# 点击'全部影评'
btn = browser.find_element_by_xpath('//*[@id="comments-section"]/div[1]/h2/span/a')
btn.click()

# 等待1秒
time.sleep(1)

# 关闭浏览器
browser.close()

步骤2和3:

代码如下:

import requests
from bs4 import BeautifulSoup

# 评论数据存储列表
comment_list = []

# 爬取前3页的评论数据
for i in range(3):
    # 构造评论页面链接
    url = f'https://movie.douban.com/subject/25868125/comments?start={i*20}&limit=20&status=P&sort=new_score'
    # 请求评论页面
    res = requests.get(url)
    # 解析评论页面
    soup = BeautifulSoup(res.text, 'html.parser')
    # 获取评论列表
    comments = soup.find_all('div', class_='comment-item')
    # 遍历评论列表,获取评论人名称、评论时间以及评论
    for comment in comments:
        user_name = comment.find('span', class_='comment-info').find('a').text.strip()
        comment_time = comment.find('span', class_='comment-info').find_all('span')[1].text.strip()
        comment_text = comment.find('span', class_='short').text.strip()
        # 将评论数据存入列表
        comment_list.append({'user_name': user_name, 'comment_time': comment_time, 'comment_text': comment_text})

# 打印评论数据
for comment in comment_list:
    print(comment)

步骤4:

代码如下:

import json

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

注意:

  • 该代码示例仅抓取前三页的评论数据,你可以根据需要修改代码来抓取更多页面的评论数据。
  • 为了防止被豆瓣网站封禁,请合理设置爬取频率,不要过于频繁地发送请求。
  • 爬取网站数据时请遵守网站的 robots.txt 协议,并尊重网站的版权和隐私政策。

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

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