0

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

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
cgrum
  • 1

1 Answers1

0

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"));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352