Search code examples
pythonseleniumwebautomation

How to close browser(ChromeDriver) on time using Python


I made a Python program that opens my Youtube playlist using Selenium and I want to close that browser when all video is watched. (I tried using time.sleep() but the problem is Youtube ads). So, is there any way I can close my browser automatically when all video is watched?


Solution

  • When the video is finished //div[@class='ytp-autonav-endscreen-button-container'] element appears so you can wait until this element appearing and then close the driver.
    You can also simply locate it by the class name 'ytp-autonav-endscreen-button-container' or other buttons / elements inside it.
    So after staring the video use

    WebDriverWait(driver, delay).until(EC.visibility_of_element_located((By.ID, 'ytp-autonav-endscreen-button-container')))
    

    where delay is time that will be enough to the video to finish.
    Lear more about webdriver explicit wait conditions here

    Don't forget to add the essential imports

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By