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

如何实现YouTube评论区滚动到底?Selenium爬虫遇难题求助

解决YouTube评论区滚动到底部的问题

你的问题核心是找错了滚动容器:YouTube的页面布局中,body并非评论区的滚动载体,所以document.body.scrollHeight返回0是正常的。评论区是一个独立的可滚动容器,需要定位到它再执行滚动操作。

正确实现步骤

  1. 使用显式等待确保评论区容器加载完成(比time.sleep更稳定)
  2. 定位评论区的滚动容器,循环执行滚动直到没有新评论加载

完整代码示例

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
import time

url = "https://www.youtube.com/watch?v=L8jN69GEBSw"
driver = webdriver.Chrome()
driver.get(url)

# 等待评论区元素加载并滚动到视野内
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "comments"))
)
driver.execute_script("arguments[0].scrollIntoView();", driver.find_element(By.ID, "comments"))
time.sleep(1)

# 定位评论区的滚动容器:YouTube评论列表嵌套在#contents元素内
comment_container = driver.find_element(By.XPATH, '//ytd-comments//div[@id="contents"]')

# 循环滚动加载所有评论
last_height = driver.execute_script("return arguments[0].scrollHeight", comment_container)
while True:
    # 滚动到容器底部
    driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", comment_container)
    time.sleep(2)  # 等待新评论加载
    new_height = driver.execute_script("return arguments[0].scrollHeight", comment_container)
    if new_height == last_height:
        break  # 高度不变,说明无更多评论
    last_height = new_height

# 后续可添加爬取评论的逻辑
# ...

driver.quit()

关键说明

  • 不用window.scrollBy的原因:评论区是页面内独立滚动区域,滚动window不会触发评论加载逻辑
  • 显式等待能确保元素加载完成后再操作,避免因页面渲染延迟导致的定位失败
  • 通过比较滚动容器的高度判断是否加载完成,避免无限循环

内容的提问来源于stack exchange,提问作者Aarush Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:50:56