I'm trying to write dynamic XPATH by for loop in java selenium WebDriver but I couldn't do it.

There's a webpage and I have to print the string content which are in the xpaths mentioned in follow.


-> This is one of them and it's going like article[1], article[2], article[3] etc.

First of all, I have to find how many articles are there and after getting the exact number, I can show the string contents regarding all article parameters by using for loop but I couldn't write it. Could you please support for my request?

  • Can you share the HTML source as formatted text? Commented Jan 19, 2019 at 17:16
  • Please share the HTML source or URL for the page. It helps in analyzing the elements in a page. Thank you..
    Commented Jan 19, 2019 at 22:29

1 Answer 1


Your code would be cleaner if you use the Selenium API and search inside each element:

List<WebElement> articles = driver.findElements(By.xpath("/html/body/div[1]/div/div/div[3]/div[2]/div/div/div/article"));

List<String> articlesText = articles.stream().map(
                                article -> 
                                return article.findElement(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.