Python 无法使用 Selenium 播放 YouTube 视频

Unable to play YouTube video using Selenium with Python

规格:Chrome:版本 81.0.4044.113(官方构建)(64 位)

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

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

解决这个问题的关闭线程可以在网上找到,例如

根据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"Browsers\chromedriver.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()

然而,Selenium 在行抛出错误:WebDriverWait(browser, 40).until(EC.frame_to_be_available_and_switch_to_it.

Unable to locate element: {"method":"xpath","selector":"//iframe[contains(@src,'https://www.youtube.com')]"}

或根据

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()

希望对您有所帮助!