Search code examples
javahtmlselenium-webdriverxpath

How to get a dynamic text in span element in Java Selenium?


I am searching on a site by selecting a date filter over the filter. I'm trying to get the total number of records shown in the filter result.

There is a phrase "Showing 1 to 50 of 130" under the records shown on the site, and I want to dynamically take this phrase and display it on the console.

I tried many things but none of them were successful.

When I take it with InnerHTML it shows the data but all records before filtering. The value of the field changes as I filter, and I want the changed value to be retrieved when I filter.

I tried to get this data with xpath and CSS selector but it didn't work.

I am sharing the final version of my code below.

System.out.println(driver.findElement(By.xpath("//span[contains(@class, 'pagination-summary')]/xpath[1]")));

That's the error message i got:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[contains(@class, 'pagination-summary')]/xpath[1]"}

Solution

  • By locator = By.xpath("//span[contains(@class, 'pagination-summary')]");
    
    WebElement element = driver.findElement(locator);
    
    String text = element.getText();
    
    System.out.println(text);
    

    In one single line

    System.out.println(driver.findElement(By.xpath("//span[contains(@class, 'pagination-summary')]")).getText());