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?
CodePudding user response:
You could look for the replay button and if it comes up exit the loop
wait=WebDriverWait(driver,10)
While True:
try:
wait.until(EC.element_to_be_clickable((By.XPATH,"//button[@aria-label='Replay']")))
break
except:
pass
Imports:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
CodePudding user response:
It depends on what functionality you are testing.
In case you don't care about actual GUI presentation and just wish to get indication that the video is finished and you can do it with some API - do it with API. This is much more fast and stable approach.
In case you need to test the actual video finished on the GUI - you should wait for the appropriate web element with Selenium.
In this case you can use the solution given by Arundeep