You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium Python截图Reddit评论时重复截取首个元素的问题求助

解决Reddit评论单独截图问题

问题原因

你的代码里用了固定的ID选择器div#t1_ikllxsq._3sf33-9rVAO_v4y0pIW_CH,HTML中ID是唯一标识,所以每次只会定位到第一条评论,导致所有截图都是同一条内容。

修正方案

  1. 改用类选择器获取所有评论:去掉固定ID,使用评论容器的共同类名_3sf33-9rVAO_v4y0pIW_CH,通过find_elements(复数方法)获取页面上所有评论元素的列表。
  2. 确保所有评论加载完成:Reddit采用懒加载机制,需要滚动页面直到没有新评论加载出来,避免遗漏内容。
  3. 遍历评论列表逐个截图:对每个评论元素单独调用截图方法,保存为不同文件。

修正后的代码

import requests
from bs4 import BeautifulSoup
import pyttsx3, pyautogui

from PIL import Image
from io import BytesIO

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path='C:\\Selenium_Drivers\\chromedriver.exe')

url = 'https://www.reddit.com/user/UoPeople09/comments/wlt4qj/what_made_you_apply_at_uopeople/'

driver.get(url)
wait = WebDriverWait(driver, 10)

# 滚动加载所有评论
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
    # 滚动到底部
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # 等待新评论加载
    driver.implicitly_wait(3)
    # 获取新的页面高度
    new_height = driver.execute_script("return document.body.scrollHeight")
    # 如果高度不再变化,说明没有新评论了
    if new_height == last_height:
        break
    last_height = new_height

# 获取所有评论元素
comments = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div._3sf33-9rVAO_v4y0pIW_CH')))

# 逐个截图保存
for idx, comment in enumerate(comments, start=1):
    # 滚动到当前评论位置,确保完全显示
    driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", comment)
    driver.implicitly_wait(1)
    comment.screenshot(f'E:\\WEB SCRAPING PROJECTS\\PROJECTS\\Reddit Scraping\\shot{idx}.png')

driver.quit()

关键说明

  • 滚动加载逻辑:通过循环滚动页面并对比前后高度,确保所有懒加载的评论都被加载出来。
  • 评论定位:用presence_of_all_elements_located等待所有评论元素加载完成,避免获取到空列表。
  • 滚动到评论位置:对每个评论执行scrollIntoView,确保评论在可视区域内,避免截图不完整。

内容的提问来源于stack exchange,提问作者Kamal Moha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 14:20:23