我要点击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)
有人知道如何处理吗?
谢谢!
答案 0 :(得分:2)
要处理嵌入式视频播放器,您需要切换到适当的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()
答案 1 :(得分:0)
始终使用名称或某些定位符切换到框架:
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()
答案 2 :(得分:0)
如果唯一的目的是播放视频,则可以使用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()
答案 3 :(得分:-1)
首先,您正在使用的二进制版本之间存在一些不兼容性,如下所示:
支持 Chrome v64-66
支持 Chrome v66-68
因此 ChromeDriver v2.37 与 Chrome浏览器v67.0
之间存在明显的不匹配根据您要在click()
上的YouTube 播放按钮上调用https://smtebooks.us/downfile/13192/building-serverless-python-web-services-zappa-pdf
的问题,您需要在切换到时引诱 WebDriverWait 所需的<iframe>
,然后再次在调用所需元素上的click()
时引发 WebDriverWait ,
#imports
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# other lines of code
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@src='https://www.youtube.com/embed/MfMydm8iXSs']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='ytp-large-play-button ytp-button']"))).click()