无法使用Selenium和Python播放YouTube视频



规格: 铬: 版本 81.0.4044.113 (官方内部版本) (64 位)

我想使用Selenium播放HTML视频。可以从以下位置访问视频链接:

https://www.youtube.com/watch?v=nXbfZL5kttM

可以在线找到解决此问题的关闭线程,例如 OP1。

根据 RP1 提供的建议,起草了以下代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

chrome_options = webdriver.ChromeOptions()
browser = webdriver.Chrome(executable_path=r"Browserschromedriver.exe",
options=chrome_options)
browser.get("https://www.youtube.com/watch?v=nXbfZL5kttM")
WebDriverWait(browser, 40).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@src='https://www.youtube.com/watch?v=nXbfZL5kttM']")))
WebDriverWait(browser, 40).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='ytp-large-play-button ytp-button']"))).click()

但是,硒在第WebDriverWait(browser, 40).until(EC.frame_to_be_available_and_switch_to_it行抛出错误。

无法找到元素: {"method":"xpath","selector":"//iframe[contains(@src,'https://www.youtube.com')]"}

或根据 RP2:

required_frame = browser.find_element_by_xpath("//iframe[contains(@src,'https://www.youtube.com')]")
browser.switch_to.frame(required_frame)
element = browser.find_element_by_xpath("//button[@aria-label='Play']")
element.click()

同样,在第browser.find_element_by_xpath行也抛出了类似的错误。

YouTube是否有可能改变了他们的框架(例如,iframe),导致之前的建议不再有效?我尝试按照此 OP3 的建议检查所有可用的iframe,但我对如何找到适合我的情况的正确iframe有点无知。

我感谢任何帮助。

编辑 1

如OP4所建议的:

video = browser.findElement(By.id("id video")) # Use the id of the video to find it.
video.click()

没有错误,但视频无法播放。

你不需要找到iframe,没有这样的。 因此,您的代码应如下所示:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Chrome()
browser.get("https://www.youtube.com/watch?v=nXbfZL5kttM")
WebDriverWait(browser, 15).until(EC.element_to_be_clickable(
(By.XPATH, "//button[@aria-label='Play']"))).click()

希望对您有所帮助!

最新更新