0

I have some code that finds all the elements, let's call them FB posts, that have a certain XPath.

Then I loop through these in a for-loop. Say there are 20 of these.

For each of these 20 elements. They have another element, let's call it a like button, inside of them.

So as I iterate through the FB posts. I should be able to select any FB post element. Then search for the Like button inside it. Via its xPath

// Get FB posts
List<WebElement> fbPostsList = driver.findElements(By.xpath("//div[contains(@data-pagelet,'FeedUnit')]"));  


// Loop through all FB posts we can see
for (WebElement element : fbPostsList) {
    
    // Find like button based on FB post element
    List<WebElement> likeLocations = element.findElements(By.xpath("//div[@aria-label='Like']"));
        
    // Loop through elements
    for (WebElement likeLocationsElement : likeLocations) {

        System.out.println(likeLocationsElement.getLocation());


    }

}

The code aboove should do exactly that. However, what I'm finding is the second "findElements" for the like button. Is basically listing every single like button. So say there were 20 FB posts in the window. It will list 20 likes buttons.

Since I am selecting a single FB post element. Inside the first for-loop. Then doing a "findElements", surly I should only be searching inside that specific element, or FB post?

1 Answer 1

3

Your problem is in the XPath expression. The Java documentation has a clear description:

When using xpath be aware that webdriver follows standard conventions: a search prefixed with "//" will search the entire document, not just the children of this current node. Use ".//" to limit your search to the children of this WebElement.

Sign up to request clarification or add additional context in comments.

1 Comment

By the way, I'm using Java! I had a javascript tag in my question by accident.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.