Selenium中如何暂停内嵌在iframe中的YouTube视频?
解决iframe内YouTube视频暂停问题
问题原因
播放视频后,初始的ytp-large-play-button大按钮会被隐藏,取而代之的是一个通用的播放/暂停切换按钮,类名是ytp-play-button。
解决方案
定位这个切换按钮并点击即可实现暂停,修改后的代码如下:
driver.get('https://demo.guru99.com/test/guru99home/') frame1 = driver.find_element(By.XPATH,"//iframe[@src='https://www.youtube.com/embed/RbSlW8jZFe8']") driver.switch_to.frame(frame1) import time time.sleep(2) # 点击大播放按钮开始播放 Ytbutton = driver.find_element(By.XPATH, "//button[@class='ytp-large-play-button ytp-button ytp-large-play-button-red-bg']") Ytbutton.click() time.sleep(2) # 定位播放/暂停切换按钮并点击实现暂停 pause_button = driver.find_element(By.XPATH, "//button[@class='ytp-play-button ytp-button']") pause_button.click()
补充优化方案
- 模拟键盘空格键控制播放/暂停(需导入
Keys类):from selenium.webdriver.common.keys import Keys # 定位视频元素并发送空格键 video = driver.find_element(By.XPATH, "//video[@class='video-stream html5-main-video']") video.send_keys(Keys.SPACE) - 用显式等待替代
sleep()提升稳定性:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待大播放按钮可点击 Ytbutton = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[@class='ytp-large-play-button ytp-button ytp-large-play-button-red-bg']")) ) Ytbutton.click() # 等待暂停按钮可点击 pause_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[@class='ytp-play-button ytp-button']")) ) pause_button.click()
内容的提问来源于stack exchange,提问作者Mr Andreson
相关产品推荐
相关产品推荐

