Selenium爬取YouTube评论遇NoSuchElementException问题求助
问题分析与解决方案
错误原因:你定位评论元素的CSS选择器#sections #contents有误,该选择器获取的是评论区整体容器而非单个评论节点,导致后续查找子元素时找不到对应内容,抛出NoSuchElementException;同时YouTube页面结构已更新,原作者名称的定位选择器也已失效。
修正后的代码
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 wait = WebDriverWait(driver, 10) driver.get("https://www.youtube.com/watch?v=vMtr0dE0jRo") # 滚动到评论区加载初始评论 comment_section = wait.until(EC.presence_of_element_located((By.ID, "comments"))) driver.execute_script("arguments[0].scrollIntoView();", comment_section) time.sleep(2) # 滚动加载更多评论 for _ in range(5): driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);") time.sleep(1.5) print("=====START CRAWLING DATA=====") # 定位单个评论线程元素 comments = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#contents ytd-comment-thread-renderer"))) for comment in comments: try: # 提取作者名称(适配当前YouTube页面结构) author_element = comment.find_element(By.CSS_SELECTOR, "#author-text span") author_name = "@" + author_element.text.strip() # 提取评论内容 comment_text_element = comment.find_element(By.ID, "content-text") comment_text = comment_text_element.text.strip() # 按要求格式输出 print(f"Author:{author_name}") print(f"Comment:{comment_text}\n") except Exception as e: # 跳过加载异常的评论,避免程序中断 continue print("Done") driver.quit()
关键调整说明
- 先滚动到评论区再加载,避免直接滚页面底部跳过评论区的问题
- 单个评论定位器修正为
#contents ytd-comment-thread-renderer,适配当前YouTube单个评论的容器结构 - 作者名称选择器更新为
#author-text span,并自动添加@前缀匹配输出格式 - 增加异常捕获,防止单个评论加载失败导致程序终止
- 调整等待与滚动间隔,提升评论加载稳定性
预期输出格式
Author:@Ian21344 Comment:Nice! Author:@Daved Comment:Looking Goooodd
内容的提问来源于stack exchange,提问作者Minh Vũ Là
相关产品推荐
相关产品推荐

