Bharat Nanwani Bharat Nanwani - 10 days ago 4
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.

driver.findElements(By.xpath("//a[contains(@href,'http://www.holidayiq.com/hotels/')]"));


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"));
elements2.findElements(By.xpath("//a[contains(@href,'http://www.holidayiq.com/hotels/')]"));


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

Answer

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 :-

elements2.findElements(By.xpath(".//a[contains(@href,'http://www.holidayiq.com/hotels/')]"));

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*='http://www.holidayiq.com/hotels/']"));
Comments