1

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.

Bharat Nanwani
  • 653
  • 4
  • 11
  • 27

2 Answers2

1

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/']"));
Community
  • 1
  • 1
Saurabh Gaur
  • 23,507
  • 10
  • 54
  • 73
1

You should build a direct xpath like this:

//*[@class='rank-bar']//a[contains(@href, 'http://www.holidayiq.com/hotels')]

as you see you are used contains, this means you could also have something like:

//*[@class='rank-bar']//a[contains(@href, 'holidayiq.com/hotels')]

and find the elements from one step like:

driver.findElements(By.xpath("//*[@class='rank-bar']//a[contains(@href, 'holidayiq.com/hotels')]"));
lauda
  • 4,153
  • 2
  • 14
  • 28