Bharat Nanwani Bharat Nanwani - 1 year ago 115
Java Question

What is the xpath to find all Anchor Elements inside another Element?

I have a problem with locating a certain element using xpath in WebDriver. Below is my approach:

Scenario 1:
Below finds all anchor Elements whose 'href' contains value provided. Using this approach I am able to locate 38 Elements. Agreed. Works as expected.


Scenario 2: I first locate a class named 'Rank-bar' which is available only once. I then use the same xpath to locate all anchor tags within this class only. Expected anchor tags is 4 However, I still find 38 Elements using this approach as well.

WebElement elements2 = driver.findElement(By.className("rank-bar"));

What is that I am doing wrong here? Please help.

Answer Source

Actually you are again searching to find anchor element on whole document context that's why you are finding same.

If you want to search anchor element on elements2 context, you need to search with .// xpath as below :-


Or you can find same thing in just on liner using cssSelector as below :-

List<WebElement> allLinks = driver.findElements(By.cssSelector(".rank-bar a[href*='']"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download