Home > Back-end >  How to get the duration of a youtube video in Sselenium Java?
How to get the duration of a youtube video in Sselenium Java?

Time:08-08

It's my code:

@Test
    public void Task4Test(){
        DriverFactory driverFactory = new DriverFactory();
        WebDriver webDriver = driverFactory.initDriver();
        webDriver.get("https://www.youtube.com/");
        webDriver.findElement(By.xpath("//*[@id='button']//*[contains(text(), 'Zaakceptuj wszystko')]")).click();
        WebDriverWait wait = new WebDriverWait(webDriver, 30);
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//*[@id='video-title'])[1]")));
        String firstVideoTitle = webDriver.findElement(By.xpath("(//*[@id='video-title'])[1]")).getText();
        System.out.println(firstVideoTitle);
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//ytd-channel-name[@id='channel-name']"  
                "/div/div/yt-formatted-string/a)[1]")));
        String firstVideoChannel = webDriver.findElement(By.xpath("(//ytd-channel-name[@id='channel-name']"  
                "/div/div/yt-formatted-string/a)[1]")).getText();
        System.out.println(firstVideoChannel);
        String firstVideoLength = webDriver.findElement(By.xpath("(//span[@id='text'])[1]")).getText();
        System.out.println(firstVideoLength);

Response:

org.openqa.selenium.NoSuchElementException: Unable to locate element: (//span[@id='text'])[1]

Element snapshot:

screenshot

CodePudding user response:

To extract the duration of a YouTube video you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following locator strategies:

  • Using cssSelector and getText():

    driver.get("https://www.youtube.com/");
    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("ytd-thumbnail-overlay-time-status-renderer.style-scope.ytd-thumbnail span.style-scope.ytd-thumbnail-overlay-time-status-renderer#text"))).getText());
    
  • Using xpath and getAttribute("innerHTML"):

    driver.get("https://www.youtube.com/");
    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@id='thumbnail' and @href]//following::div[1]//span"))).getAttribute("innerHTML"));
    

CodePudding user response:

You should check if the video is live or not. Live videos do not have duration until its finished streaming.

  • Related