Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 无法使用selenium和python在youtube上播放视频_Python 3.x_Selenium_Selenium Webdriver - Fatal编程技术网

Python 3.x 无法使用selenium和python在youtube上播放视频

Python 3.x 无法使用selenium和python在youtube上播放视频,python-3.x,selenium,selenium-webdriver,Python 3.x,Selenium,Selenium Webdriver,这是我的代码: 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_cha

这是我的代码:

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"}

您错过了等待/延迟时间。
紧接着
browser.get(“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();

该程序给出了未定义名称“driver”警告。这是因为您将驱动程序实例称为
浏览器
,而不是通常所称的“driver”。我已更新了答案。我尝试了…(浏览器,20)…但该程序给出了TimeoutException…(浏览器,5)…有时工作有时不工作。我无法理解。1)您的internet连接速度慢,因此您定义的超时有时不够?2)您在代码中是否在预期条件下使用隐式等待?是的,我的internet连接速度慢