[Python] Play YouTube video until finished

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am using a Selenium to code python script to search and play a YouTube video.

    This is my code:

    import time
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from webdriver_manager.chrome import ChromeDriverManager
    from selenium.webdriver.common.by import By
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    # Defining video name
    video_name = "4k art"

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
    driver.maximize_window()

    wait = WebDriverWait(driver, 3)
    presence = EC.presence_of_element_located
    visible = EC.visibility_of_element_located

    # Navigate to url with video being appended to search_query
    driver.get('https://www.youtube.com/results?search_query={}'.format(str(video_name)))

    # play the video
    wait.until(visible((By.ID, "video-title")))
    driver.find_element(By.ID, "video-title").click()


    # Wait for video to end


    So, everything works fine, but I would like to know what is the best way to have the script wait until the video is finished before finishing? I saw different ways to do so using YouTube API or using Selenium with elements appearing. Is there a preferred way to do it?

    Continue reading...

Compartilhe esta Página