Vicko
Vicko

Reputation: 254

Trying to get the text out of a List of webelements with Selenium WebDriver

In my code, I try to find all elements with a specific name, then try taking each elements' descendant and get its title, link and price. The price I'm having issues with because it sticks to the price tag of the first element from the WebElements list.

List<WebElement> autos = driver.findElements(By.xpath("//section[contains(@class ,'ui-search-results')]/ol/li//a[@class = 'ui-search-result__content ui-search-link']"));
        for(WebElement auto : autos) {
            String model = auto.getAttribute("title");
            String page = auto.getAttribute("href");
            String price = auto.findElement(By.xpath("//span[@class = 'price-tag-fraction']")).getText();
            System.out.println(model + page + price);
            
        }

Console is printing model and page just fine but the price is always the same one. I already tested the site and there is a price-tag-fraction per element.

Upvotes: 0

Views: 3441

Answers (1)

JeffC
JeffC

Reputation: 25611

When you use XPath and want to start searching from a specific element, you need to add a . to the start of the XPath. In your case

"//span[@class = 'price-tag-fraction']"

becomes

".//span[@class = 'price-tag-fraction']"

Your updated code

List<WebElement> autos = driver.findElements(By.xpath("//section[contains(@class ,'ui-search-results')]/ol/li//a[@class = 'ui-search-result__content ui-search-link']"));
for(WebElement auto : autos) {
    String model = auto.getAttribute("title");
    String page = auto.getAttribute("href");
    String price = auto.findElement(By.xpath(".//span[@class = 'price-tag-fraction']")).getText();
    System.out.println("Model: %s, Page: %s, Price: %s".formatted(model, page, price));            
}

NOTE: I changed your print statement to make it easier to read. You could also write these to a CSV file and then open them later in Excel, etc. as a table.

Upvotes: 1

Related Questions