豆瓣电影评论抓取 - Python Selenium & BeautifulSoup
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
from bs4 import BeautifulSoup
import json
import time
# 设置Chrome浏览器路径
browser = webdriver.Chrome('D:/chromedriver.exe')
# 打开网页
url = 'https://movie.douban.com/subject/25868125/'
browser.get(url)
# 点击“全部影评”
button = browser.find_element_by_xpath('//*[@id="comments-section"]/div[1]/h2/span/a')
button.click()
# 等待网页加载完成
time.sleep(5)
wait = WebDriverWait(browser, 10)
wait.until(EC.presence_of_element_located((By.ID, 'comments-section')))
# 读取网页源代码
html = browser.page_source
soup = BeautifulSoup(html, 'html.parser')
# 获取第一页评论
comments = []
for item in soup.find_all('div', class_='comment-item'):
name = item.find('a', class_='').get_text().strip() # 评论人名称
time = item.find('span', class_='comment-time').get_text().strip() # 评论时间
content = item.find('span', class_='short').get_text().strip() # 评论内容
comments.append({'name': name, 'time': time, 'content': content})
# 获取2-3页评论
for i in range(1, 3):
url = 'https://movie.douban.com/subject/25868125/comments?start={}&limit=20&status=P&sort=new_score'.format(i*20)
browser.get(url)
time.sleep(5)
wait.until(EC.presence_of_element_located((By.ID, 'comments-section')))
html = browser.page_source
soup = BeautifulSoup(html, 'html.parser')
for item in soup.find_all('div', class_='comment-item'):
name = item.find('a', class_='').get_text().strip() # 评论人名称
time = item.find('span', class_='comment-time').get_text().strip() # 评论时间
content = item.find('span', class_='short').get_text().strip() # 评论内容
comments.append({'name': name, 'time': time, 'content': content})
time.sleep(5)
# 存储为json文件
with open('comments.json', 'w', encoding='utf-8') as f:
json.dump(comments, f, ensure_ascii=False)
# 关闭浏览器
browser.quit()
代码功能:
- 使用 Selenium 打开豆瓣电影页面,并点击“全部影评”。
- 使用 BeautifulSoup 解析网页源代码,提取评论信息(评论人、评论时间、评论内容)。
- 将提取的评论信息保存到 JSON 文件中。
注意:
- 请先安装必要的库:
pip install selenium beautifulsoup4 - 将
D:/chromedriver.exe替换为你的 Chrome 浏览器驱动程序路径。 - 豆瓣网站可能存在反爬机制,如果代码无法正常运行,可能需要调整代码或使用代理服务器。
代码优化:
- 添加了等待时间,以确保页面加载完成。
- 使用
time.sleep()方法,在每个页面加载完成后等待5秒钟,以避免请求过快导致被网站封锁。 - 添加了
ensure_ascii=False参数,确保 JSON 文件中可以保存中文评论内容。
希望以上代码和说明对您有所帮助。
原文地址: https://www.cveoy.top/t/topic/oBhi 著作权归作者所有。请勿转载和采集!