findElement not working as expected in for-each loop

CitrisLemon :

I'm completely stuck and have no idea why I'm getting the output that I am. Here's the relevant snippet.

WebElement section = driver.findElement(By.xpath("//div[contains(@class,'_main')]"));
List<WebElement> searchResults = new ArrayList<WebElement>();
searchResults.addAll(section.findElements(By.xpath("//div[contains(@class,'_listing')]")));
for (WebElement element : searchResults) {
    System.out.println(element.getAttribute("innerHTML"));
    System.out.println(element.findElement(By.xpath("//p[contains(@class,'_2tux')]")).getText());

    currentlistings.add(newListing('f',element.findElement(By.xpath("//a[contains(@class,'_1oem')]")).getAttribute("href"),
    element.findElement(By.xpath("//p[contains(@class,'_2tux')]")).getText(),
    element.findElement(By.xpath("//div[contains(@class,'_f3l _4x3g')]")).getText()));
}

The code seemingly functions fine when storing elements to the list, the size is correct and when I iterate through the list elements innerHTML outputs as expected.

However when I then try and use findElement on each of the iterated elements, it seemingly reads the HTML from the element at index 0, even though the command immediately prior outputs the html from the correct index. Any pointers would be much appreciated.

Jortega :

You need to use .//.

element.findElement(By.xpath(".//p[contains(@class,'_2tux')]")).getText(),
element.findElement(By.xpath(".//div[contains(@class,'_f3l _4x3g')]")).getText()));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=352770&siteId=1