《穿靴子的猫2》豆瓣电影影评爬取代码 - 使用 Selenium 和 BeautifulSoup
导入必要的库
from selenium import webdriver from selenium.webdriver.chrome.options import Options import time import requests from bs4 import BeautifulSoup import json
创建浏览器对象
options = Options() options.add_argument('--headless') # 无头模式 options.add_argument('--disable-gpu') driver = webdriver.Chrome(chrome_options=options)
设置请求头
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' }
定义要爬取的电影页面 URL
movie_url = 'https://movie.douban.com/subject/25868125/'
使用 Selenium 访问电影页面
driver.get(movie_url)
定位并点击“更多”按钮,加载全部评论
btn_more = driver.find_element_by_xpath("//a[@class='more']") btn_more.click()
等待页面加载
time.sleep(2)
初始化评论列表
comment_list = []
循环爬取每页评论
for page in range(0, 201, 20): # 从第1页到第11页,每页20条评论 # 构建评论页面的 URL comment_url = f'https://movie.douban.com/subject/25868125/comments?start={page}&limit=20&sort=new_score&status=P' driver.get(comment_url)
# 等待页面加载
time.sleep(2)
# 使用 BeautifulSoup 解析网页
soup = BeautifulSoup(driver.page_source, 'html.parser')
comments = soup.find_all('div', class_='comment-item')
# 提取每条评论信息
for comment in comments:
name = comment.find('span', class_='comment-info').a.text
time = comment.find('span', class_='comment-time').text.strip()
content = comment.find('span', class_='short').text.strip()
comment_list.append({'name': name, 'time': time, 'content': content})
保存数据到 JSON 文件
with open('douban_movie_comments.json', 'w', encoding='utf-8') as f: json.dump(comment_list, f, ensure_ascii=False) # ensure_ascii=False 保证中文不乱码
关闭浏览器
driver.quit()
原文地址: https://www.cveoy.top/t/topic/oA55 著作权归作者所有。请勿转载和采集!