How to close browser(ChromeDriver) on time using Python

Viewed 406

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?

2 Answers

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

I suggest to make in in steps.

First step:

Wait for the last video in playlist:

By text:

last_video = driver.find_element_by_css_selector("#secondary .index-message.style-scope.ytd-playlist-panel-renderer:nth-child(1)").text == "10 /10"

Or by waiting for the last element in the playlist directly:

last_video = driver.find_element_by_css_selector("#secondary #items>.style-scope.ytd-playlist-panel-renderer:last-of-type").get_attribute("selected")

Second step:

After the first condition is true, wait for this video to finish, with this locator (Replay button)

video_ends = driver.find_element_by_css_selector(".ytp-chrome-controls button[title=Replay]")

For this you'll need to import:

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

And use it like this:

wait = WebDriverWait(driver, timeout_in_seconds)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#secondary .index-message.style-scope.ytd-playlist-panel-renderer:nth-child(1)").text == "10 /10")))

Timeout will depend of the length of playlist.

It is not a quick task, nobody will agree to finish it for you here.

Related