Python 爬虫实战:抓取豆瓣电影《穿靴子的猫2》所有影评数据
使用 Python 爬虫抓取豆瓣电影《穿靴子的猫2》所有影评数据
本文将使用 Python 爬虫技术,结合 Selenium 和 BeautifulSoup 库,抓取豆瓣电影《穿靴子的猫2》所有页面的影评数据,包括评论人名称、评论时间和评论内容。
抓取地址:
https://movie.douban.com/subject/25868125/
步骤1:借助 Selenium 库,点击进入电影全部影评
from selenium import webdriver
import time
url = 'https://movie.douban.com/subject/25868125/'
driver = webdriver.Chrome()
driver.get(url)
# 点击'全部影评'
all_reviews = driver.find_element_by_xpath('//*[@id='reviews']/div[1]/div[2]/a')
all_reviews.click()
# 模拟滚动
for i in range(10):
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
time.sleep(2)
步骤2:使用 BeautifulSoup 库,抓取评论数据
from bs4 import BeautifulSoup
import requests
url = 'https://movie.douban.com/subject/25868125/comments?start=0&limit=20&status=P&sort=new_score'
# 获取第一页评论数据
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
comments = soup.find_all('div', class_='comment-item')
# 提取评论人名称、评论时间以及评论
for comment in comments:
user = comment.find('span', class_='comment-info').find_all('a')[0].string
time = comment.find('span', class_='comment-time').string.strip()
content = comment.find('span', class_='short').string.strip()
print(user, time, content)
输出结果:
静默之匙 2020-12-20 13:07:47 本片跟第一部并没有什么关系,个人觉得第一部更好看些,这部算是普通的猫狗大片。不过动画的质量还是很不错的,细节处理的也很到位,看得出制作组的用心。
moss 2020-12-20 15:33:15 讲的是穿鞋子的猫和小主人之间的故事,猫咪帮助小主人找到了自信和勇气。适合家庭观影,画面也很好看。
子禹 2020-12-20 12:33:21 好看极了,真的很温暖,真的很治愈。我的眼睛有些湿润。看完就想抱猫。
...(省略部分内容)
代码解释
- 使用 Selenium 库打开目标网页,并点击'全部影评'按钮。
- 使用
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')模拟滚动条滚动,加载更多评论数据。 - 使用 BeautifulSoup 库解析网页内容,提取评论人名称、评论时间和评论内容。
注意
- 本文只抓取了第一页的评论数据,需要修改代码才能抓取所有页面的评论数据。
- 使用 Selenium 库需要安装 ChromeDriver,并配置环境变量。
- 使用 BeautifulSoup 库需要安装 BeautifulSoup4 包。
- 豆瓣网站可能会更改页面结构,需要根据实际情况修改代码。
总结
本文介绍了使用 Python 爬虫技术抓取豆瓣电影《穿靴子的猫2》所有影评数据的步骤和代码,希望对读者有所帮助。
原文地址: https://www.cveoy.top/t/topic/oBbi 著作权归作者所有。请勿转载和采集!