如何通过selenium找到数据挂钩中存在的元素

时间:2017-12-05 08:53:29

标签: java selenium-webdriver

我的HTML代码为:

<a class="a-size-base a-link-normal review-title a-color-base a-text-bold" data-hook="review-title" href="/gp/customer-reviews/R252N8IFRXV8TW/ref=cm_cr_getr_d_rvw_ttl?ie=UTF8&ASIN=B071NZZHF9">Security concern</a>

并且我必须通过data-hook搜索元素,因为类名对于其他属性也是常见的,并且href和link-text是动态的,因为它正在为下一个元素进行更改,因为我需要获取多个元素

我可以通过数据挂钩搜索它吗?如果有,有人可以帮助我!

3 个答案:

答案 0 :(得分:0)

当然可以。

CSS:

driver.findElement(By.cssSelector("a[data-hook='review-title']"));

Xpath的:

driver.findElement(By.xpath("//a[@data-hook='review-title']"));

答案 1 :(得分:0)

如果您需要多个数据挂钩项,也可以使用以下代码。

List<WebElement> list = driver.findElements(By.className("review-title"));

for(WebElement elem : list){
    System.out.println(elem.getAttribute("data-hook"));
}

答案 2 :(得分:0)

根据您共享的HTML通过data-hook属性查找元素,您可以使用以下代码行:

driver.findElement(By.xpath("//a[@data-hook='review-title']"));

虽然您提到class name很常见但最好将class name属性保留在xpath中,如下所示:

driver.findElement(By.xpath("//a[@class='a-size-base a-link-normal review-title a-color-base a-text-bold' and @data-hook='review-title']"));

此外,虽然你提到href正在改变,但我建议使用所有三个属性的组合来唯一地将元素标识为:

driver.findElement(By.xpath("//a[@class='a-size-base a-link-normal review-title a-color-base a-text-bold' and contains(@href,'/gp/customer-reviews/') and @data-hook='review-title']"));