简体   繁体   English

在另一个Element内查找所有Anchor元素的xpath是什么?

[英]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. 我在使用WebDriver中的xpath定位某个元素时遇到问题。 Below is my approach: 下面是我的方法:

Scenario 1: Below finds all anchor Elements whose 'href' contains value provided. 方案1:在下面查找其“ href”包含所提供值的所有锚点元素。 Using this approach I am able to locate 38 Elements. 使用这种方法,我能够找到38个元素。 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. 方案2:我首先找到一个名为“ Rank-bar”的类,该类只能使用一次。 I then use the same xpath to locate all anchor tags within this class only. 然后,我使用相同的xpath仅定位此类中的所有定位标记。 Expected anchor tags is 4 However, I still find 38 Elements using this approach as well. 预期的锚标记为4。但是,我仍然可以找到38个使用此方法的元素。

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. 请帮忙。

You should build a direct xpath like this: 您应该像这样建立一个直接的xpath:

//*[@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')]"));

Actually you are again searching to find anchor element on whole document context that's why you are finding same. 实际上,您再次在整个文档上下文中寻找anchor元素的原因,这就是您查找相同元素的原因。

If you want to search anchor element on elements2 context, you need to search with .// xpath as below :- 如果要在elements2上下文中搜索anchor元素,则需要使用.// xpath进行搜索,如下所示:

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 :- 或者,您可以使用cssSelector在衬板上找到相同的内容,如下所示:-

List<WebElement> allLinks = driver.findElements(By.cssSelector(".rank-bar a[href*='http://www.holidayiq.com/hotels/']"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM