【问题标题】:Being not able to play videos on youtube with selenium and python无法使用 selenium 和 python 在 youtube 上播放视频
【发布时间】:2021-05-29 17:57:51
【问题描述】:

这是我的代码:

from selenium import webdriver
from time import sleep
    
    
browser=webdriver.Chrome(r"C:\Users\Desktop\chromedriver.exe")
browser.maximize_window()
    
 
browser.get("https://www.youtube.com/watch?v=3yjO6yfHLcU&ab_channel=TRT%C4%B0zleTRT%C4%B0zleDo%C4%9Fruland%C4%B1") 

browser.find_element_by_class_name("ytp-play-button ytp-button").click()
sleep(2)

我无法使用 selenium 和 python 在 YouTube 上播放视频。我怎样才能做到这一点? 这是错误:

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".ytp-play-button ytp-button"}

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver


    【解决方案1】:

    您在那里错过了等待/延迟。
    browser.get("the_url) 之后,页面仍然没有加载,需要一些时间,所以您尝试单击的元素仍然不存在。
    您必须添加一些延迟。
    正确的做法是添加显式等待,如下所示:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    element = WebDriverWait(browser, 20).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, ".ytp-play-button ytp-button")))
    
    element.click();
    

    【讨论】:

    • 程序给出 Undefined name 'driver' 警告。
    • 那是因为您将驱动程序实例称为browser,而不是通常称为“驱动程序”。我已经更新了答案
    • 我试过 ...( browser, 20)... 但程序给出 TimeoutException ..( browser, 5)... 有时工作有时不行。我无法理解。
    • 1) 您的互联网连接速度是否很慢,因此您定义的超时有时不够? 2)您是否在代码中额外使用了隐式等待以及预期的条件?
    • 是的,我的网速很慢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    相关资源
    最近更新 更多