0

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.

/html/body/div[1]/div/div/div[3]/div[2]/div/div/div/article[1]/header/div/div  

-> 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? – Bence Kaulics Jan 19 at 17:16
  • Please share the HTML source or URL for the page. It helps in analyzing the elements in a page. Thank you.. – SQA_LEARN Jan 19 at 22:29
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(
                                   By.xpath("/header/div/div")).getText())
                                .collect(Collectors.toList());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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