Python YouTube评论机器人异常:无法滚动评论区并提交评论
问题分析与解决方案
你的代码主要存在以下几个核心问题,导致机器人在进入视频后停止运行:
错误切换到iframe
YouTube视频页面的评论区并不在iframe中,强行切换iframe会让后续所有元素查找操作都处于错误的上下文,直接导致找不到评论相关元素。滚动距离不足
window.scrollTo(0,200)的滚动距离太短,根本无法到达页面下方的评论区,需要滚动到足够的位置触发评论区加载。元素定位错误
你使用的评论框IDcomment和提交按钮IDsubmit-button不符合YouTube当前的页面结构,需要使用正确的选择器。固定sleep的不稳定性
过多固定时长的time.sleep可能导致元素还未加载完成就执行后续操作,建议用显式等待替代。
修改后的完整代码
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 def job(): options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option("useAutomationExtension", False) options.add_argument('--disable-blink-features=AutomationControlled') driver = webdriver.Chrome(options=options) driver.maximize_window() driver.get("https://accounts.google.com/signin/v2/identifier") # 登录邮箱 email = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.ID, "identifierId"))) email.send_keys("你的邮箱") driver.find_element(By.ID, "identifierNext").click() # 登录密码 password = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='Passwd']"))) password.send_keys("你的密码") driver.find_element(By.ID, "passwordNext").click() # 等待登录完成并进入趋势页 WebDriverWait(driver, 15).until(EC.url_contains("youtube.com")) driver.get("https://www.youtube.com/feed/trending") # 点击第一个视频 video = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ytd-video-renderer:first-child a#thumbnail"))) video.click() # 滚动到评论区并等待加载 WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.TAG_NAME, "ytd-comments"))) # 滚动到评论区容器位置 comment_section = driver.find_element(By.TAG_NAME, "ytd-comments") driver.execute_script("arguments[0].scrollIntoView();", comment_section) time.sleep(2) # 短暂等待评论区完全加载 # 定位评论输入框并输入内容 comment_box = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ytd-comment-simplebox-renderer #contenteditable-root"))) comment_box.click() comment_box.send_keys("你的评论内容") # 定位提交按钮并点击 submit_button = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ytd-comment-simplebox-renderer #submit-button"))) submit_button.click() time.sleep(5) driver.quit() job()
额外说明
- 注意替换代码中的
你的邮箱、你的密码、你的评论内容为实际信息。 - 如果遇到人机验证,可能需要手动完成,或者添加应对验证的逻辑。
- YouTube的页面结构可能会更新,若后续再次出现定位问题,需要重新检查元素选择器。
内容的提问来源于stack exchange,提问作者bladesofcompility
相关产品推荐
相关产品推荐

