豆瓣电影评论爬取 - 使用Selenium和BeautifulSoup

本代码使用Python的Selenium和BeautifulSoup库爬取豆瓣电影评论,并将其存储为JSON格式。

代码示例:

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

# 设置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()

# 等待网页加载完成
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)
    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})

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

# 关闭浏览器
browser.quit()

代码说明:

  1. 使用 webdriver.Chrome() 打开Chrome浏览器,并设置等待时间为10秒。
  2. 使用 browser.get() 打开目标网页。
  3. 使用 find_element_by_xpath() 找到“全部影评”按钮并点击。
  4. 使用 WebDriverWait() 和 EC.presence_of_element_located() 等待网页加载完成。
  5. 使用 BeautifulSoup 解析网页源代码。
  6. 使用循环遍历所有评论,并提取评论人名称、评论时间和评论内容。
  7. 将评论数据存储为JSON格式。
  8. 关闭浏览器。

使用说明:

  1. 确保已安装Selenium和BeautifulSoup库。
  2. 下载Chrome浏览器驱动程序(chromedriver.exe),并将路径修改为你的实际路径。
  3. 修改代码中的 url 参数为目标豆瓣电影页面的URL。
  4. 运行代码,并检查生成的文件 comments.json。

注意事项:

  • 网站可能随时更改结构,需要根据实际情况修改代码。
  • 爬取网站数据时,请遵守网站的爬取规则,避免过度爬取导致网站封禁。
  • 可以根据需要修改代码,例如爬取更多页面的评论,或者提取其他信息。

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

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