首页 > 解决方案 > 如何通过selenium和python点击嵌入在smtebook中的youtube视频的播放按钮

问题描述

我想点击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)

任何人都知道如何处理它?

谢谢!

标签: python-3.xseleniumselenium-webdriverxpathwebdriverwait

解决方案


为了能够处理嵌入式视频播放器,您需要切换到适当的 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()

推荐阅读