【问题标题】:How to click on the play button of a youtube video embedded within smtebook through selenium and python如何通过selenium和python点击嵌入在smtebook中的youtube视频的播放按钮
【发布时间】:2018-08-09 09:58:32
【问题描述】:

我想点击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.x selenium selenium-webdriver xpath webdriverwait


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        如果只是为了播放视频,可以使用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()
        

        【讨论】:

        • 如果 chrome 设置被配置为不自动播放视频,那么这个解决方法显然不起作用
        猜你喜欢
        • 1970-01-01
        • 2017-02-22
        • 1970-01-01
        • 2015-06-20
        • 2021-11-03
        • 2020-08-25
        • 2014-11-26
        • 2014-12-01
        • 2012-07-09
        相关资源
        最近更新 更多