我遇到了无法找到xpath的keep throw错误,因为我设置了打开此xpath以插入数据的循环。虽然我设置等待存在的时间为60秒但仍然无法找到它。我一直在尝试通过使用标题或状态调用此方法,因此它仍然无法正常工作。请建议
HTML:
<a href="javascript: void edit('edit_total_amt')" title="Override total tax amount" onmouseover="status='Override total tax amount'; return true">91.14</a>
代码:
public void clickOnItemTax () {
By xPath = By.xpath("//a[contains(@href,'edit_total_amt')]");
this.sleep(3);
if (this.waitForExistence(xPath,60)) {
WebElement domLink = linkGet(xPath);
domLink.click();
} else {
JLog.fail("Unable to find a writable item taxdialog!");
}
}
-waitforExistence
public boolean waitForExistence(By by, int timeoutSeconds){
boolean exists = false;
Long polling_interval = (long) 250;
Long timeout = (long) timeoutSeconds * 1000; // in seconds
Long elapsed = (long) 0;
while (elapsed <= (timeout)) {
if (exists(by)) {
exists = true;
break;
}
try {
Thread.sleep(polling_interval);
} catch (InterruptedException e) {
JLog.warning(JLog.getStackTraceAsString(e));
break;
}
elapsed += polling_interval;
}
if (elapsed >= timeout) {
JLog.warning("waitForExistence waited for " + timeout/1000 + " seconds, but unable to find: " + by.toString());
}
return exists;
}
谢谢你
答案 0 :(得分:2)
如果是内部公司网页,我建议您提供一个“内容”网址。让你的生活更轻松如果没有,你可以这样做。当您在Selenium中使用隐式或显式等待时间时,我总是会为编写自己的等待方法的人感到惊讶。
前者如下所示,使用此方法唯一需要注意的是,在查找元素时,它总会等待这么久。然而,编写脚本寻找元素并且不会使代码膨胀是一种更安全的方式:
driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS);
if (driver.findElements(By.cssSelector("//*[@title=\"Override total tax amount\"]")).size()!=0)
{
driver.findElement(By.cssSelector("//*[@title=\"Override total tax amount\"]")).click();
}
else
{
JLog.fail("Unable to find a writable item taxdialog!");
}
明确的方法如下,其中10是你的秒:
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("//*[@title=\"Override total tax amount\"]")));
有关详细信息,请参阅以下链接。 http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp