我试图点击一个特定的公司,并从这个网站http://demo.guru99.com/test/web-table-element.php#在控制台中打印公司名称,我没有得到这样的元素异常这是我的代码:
driver.findElement(By.xpath("//a[contains(text(),'Marico Ltd.')]/parent::td")).click();
您可以使用循环来通过刷新页面直到显示来搜索元素。
注意:如果元素不显示,它将进入无限循环,因此在某个点中断它。
方法# 1:循环检查10次所需元素是否显示
driver.get("http://demo.guru99.com/test/web-table-element.php#");
int i = 0;
while (i < 10) {
if (isElementDisplayed()) {
driver.findElement(By.xpath("//a[contains(text(),'Marico Ltd.')]/parent::td")).click();
System.out.println("Navigated to Guru99 Bank at " + i + " iteration.");
break;
} else {
driver.navigate().refresh();
i++;
}
}
方法# 2:如果元素存在,检查并返回boolean
值为true
,否则返回false
public static boolean isElementDisplayed() {
try {
driver.findElement(By.xpath("//a[contains(text(),'Marico Ltd.')]/parent::td"));
return true;
} catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}
输出:
Navigated to Guru99 Bank at 4 iteration.
您应该获取元素列表并检查其大小是否存在:
List<WebElement> list = driver.findElements(By.xpath("//a[contains(text(),'Marico Ltd.')]"));
Assert.assertTrue("Text not found!", list.size() > 0);
你也不应该在findElement
中使用/parent::td
。接下来可以单击断言
List.get(0).click()
您的定位器不一定是错误的,但在这种情况下,它不工作,但我们可以修复它。问题是,当Selenium试图单击一个元素时,它会找到元素的x-y维度,然后单击该元素的确切中心。在这种情况下,TD的确切中心没有A标记(超链接)。
解决这个问题最简单的方法就是使用定位器点击A标签,//a[contains(text(),'Marico Ltd.')]
在对元素进行操作之前,使用WebDriverWait
来确保元素准备就绪始终是最佳实践。
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(),'Marico Ltd.')]"))).click();