【问题标题】:How to click on the play button of a youtube video embedded using Python如何单击使用 Python 嵌入的 youtube 视频的播放按钮
【发布时间】:2020-08-25 22:52:04
【问题描述】:

我正在尝试让 Python 播放嵌入在网站 (https://harsh10822.wixsite.com/intro) 中的视频。 我尝试使用 ID、xpath 等,但它没有锻炼。 这里有一个类似的问题(How to click on the play button of a youtube video embedded within smtebook through selenium and python)但我不知道如何应用代码。 如果您可以通过提供代码来帮助我,我将非常高兴。 谢谢你

【问题讨论】:

    标签: python python-3.x selenium youtube-api


    【解决方案1】:

    这应该可行。

    driver = webdriver.Firefox()
    driver.get('https://harsh10822.wixsite.com/intro')
    time.sleep(5)
    video = driver.find_element_by_id('video-player-comp-ka1067od')
    video.click()
    

    在这种情况下等待很重要,因为嵌入的视频不会立即随页面加载,因此 selenium 需要等待。您可以将 5 秒更改为任何适合您的数字。

    【讨论】:

    • 或者您可以在驱动程序初始化后立即发出driver.implicitly_wait(5),不要发出对sleep的调用,然后对find_element_by_id的调用应该等待最多5秒它超时。 但是如果元素在 5 秒之前出现,你就不会不必要地等待额外的时间。所以你不妨把秒数任意大。
    • 那将是理想的,但在这种情况下,页面在您播放视频之前完成加载。换句话说,首先加载页面,然后在页面加载完成后加载视频。所以我能看到的唯一解决方案是使用time.sleep() 方法。
    • 我认为单击该 ID 无效。这是一个等待正确元素加载的问题。
    • 我发布的代码有效,但如果您有其他想法,我很乐意看到它。
    • 我应该说我确实第二次尝试了你的答案并且它确实有效,所以我赞成它,
    【解决方案2】:

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

    但这使用了一种稍微不同的技术,而不是 WebDriverWait 或睡眠固定的秒数,如果你的睡眠时间超过了必要的时间,这可能是一种浪费。

    改为调用driver.implicitly_wait(10)。然后,任何尝试定位元素的调用都会在超时之前隐式等待最多 10 秒以使元素出现,但不会等待超过必要的时间。这只是一个知道要查找哪些元素以及在哪里查找的问题:

    driver = webdriver.Firefox()
    
    driver.implicitly_wait(10) # wait for up to 10 seconds before timeout for any find operation
    
    driver.get('https://harsh10822.wixsite.com/intro')
    driver.switch_to.frame(driver.find_element_by_xpath('//iframe[starts-with(@src, "https://www.youtube.com/embed")]')) # switch to iframe
    button = driver.find_element_by_xpath('//button[@aria-label="Play"]') # look for button
    button.click()
    

    【讨论】:

      【解决方案3】:

      确保下载特定的网络驱动程序并将其放置在保存代码的目录中。作为参考,您可以参考 Tech With Tim selenium 教程。

      from selenium import webdriver
      from selenium.webdriver.common.keys import Keys
      import time
      video=input()
      driver=webdriver.Chrome()
      driver.get("https://youtube.com")
      search=driver.find_element_by_id("search")
      time.sleep(2)
      search.send_keys(video,Keys.RETURN)
      time.sleep(2)
      play=driver.find_element_by_id("video-title")
      play.send_keys(Keys.RETURN)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-22
        • 2012-07-09
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        • 2016-03-19
        • 2015-06-20
        • 2023-04-01
        相关资源
        最近更新 更多