【问题标题】:Unable to play YouTube video using Selenium with Python无法使用 Selenium 和 Python 播放 YouTube 视频
【发布时间】:2020-04-19 06:05:21
【问题描述】:

规格:Chrome:版本 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"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

无法定位元素: {"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()

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

【问题讨论】:

  • 您要播放的视频的链接是什么?
  • 嗨@0m3r,请参考编辑的帖子。

标签: python selenium iframe html5-video


【解决方案1】:

您不需要找到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()

希望对你有帮助!

【讨论】:

  • 跟进,你怎么知道没有这个iframe?如果我想播放来自不同网站的 HTML 视频,这些知识可能会对我有所帮助。
  • @balandongiv,不客气!例如,您可以在 Google Chrome 的开发者工具中检查该页面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 2014-07-13
  • 2021-05-29
  • 2011-09-06
相关资源
最近更新 更多