如何通过 selenium 和 python 单击嵌入在 smtebook 中的 youtube 视频的播放按钮

How to click on the play button of a youtube video embedded within smtebook through selenium and python

我想点击 https://smtebooks.us/downfile/13192/building-serverless-python-web-services-zappa-pdf

中的 youtube 播放

我的代码是:

browser.switch_to.frame(0) 
element = browser.find_element_by_xpath("//button[@class='ytp-large-play-button ytp-button']")
element.click()

但找不到元素

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@class='ytp-large-play-button ytp-button']"}
(Session info: chrome=67.0.3396.99)
(Driver info: chromedriver=2.37.543627 (63642262d9fb93fb4ab52398be4286d844092a5e),platform=Windows NT 10.0.17134 x86_64)

有人知道如何处理它吗?

谢谢!

始终使用名称或某些定位器切换到框架:

required_frame = driver.find_element_by_xpath("//iframe[contains(@src,'https://www.youtube.com')]")
driver.switch_to.frame(required_frame) 

然后,下面的代码有效,

element = driver.find_element_by_xpath("//button[@aria-label='Play']")
element.click()

为了能够处理嵌入式视频播放器,您需要切换到适当的 iframe 并等待按钮出现在 DOM:

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

browser.switch_to.frame(browser.find_element_by_xpath('//iframe[starts-with(@src, "https://www.youtube.com/embed")]'))
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '//button[@aria-label="Play"]'))).click()

如果只是为了播放视频,您可以使用 driver.refresh()

刷新页面

例如,下面的例子适合我。

from selenium import webdriver
import time

def watchvideo():
driver = webdriver.Chrome(executable_path="/Users/kamlesh/chromedriver")
driver.get("https://www.youtube.com/watch?v=gXpzn8PAScw")
driver.refresh()
time.sleep(170)
driver.close()