【问题标题】:How can I overcome Element id exception in Selenium?如何克服 Selenium 中的 Element id 异常?
【发布时间】:2012-08-08 10:46:35
【问题描述】:
在 UiBinder 本身中为 GWT 小部件设置“id”。
例如。
还在 *.gwt.xml 中添加了
然后我在 Selenium 测试用例中尝试这个
WebElement element = driver.findElement(By.id("gwt-debug-loginButton"));
有时它可以正常工作。但有时它会抛出以下异常,
无法定位元素:
{"method":"id","selector":"gwt-debug-loginButton"} 命令持续时间或
超时:62 毫秒
我需要更新什么?
谁能帮帮我?
【问题讨论】:
标签:
gwt
selenium
selenium-webdriver
gwt2
selenium-server
【解决方案1】:
使用WebDriverWait,在一定时间后搜索元素。像这样。
try {
(new WebDriverWait(driver, seconds, delay)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
try {
WebElement el = d.findElement(By.id("gwt-debug-loginButton"));
return true;
} catch (Exception e) {
return false;
}
}
});
} catch (TimeoutException t) {
//Element not found during the period of time
}
【解决方案2】:
当您尝试使用selenium WebDriver 在您的网页上查找任何元素时。
您可以使用Implicit Wait 或Explicit Wait 让driver 等到页面完全加载完成
隐式等待示例(此代码通常在您初始化驱动程序后使用)-
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
如果驱动程序找不到您要查找的元素,上述语句使驱动程序等待 10 秒。如果驱动程序即使在 10 秒后也找不到它,驱动程序会抛出异常。
显式等待的示例 - 在您的情况下,这专门用于单个 WebElement -
new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.id("gwt-debug-loginButton")));
上面的代码会让驱动等待20秒直到找到元素。如果即使在 20 秒后也找不到该元素,则会引发 TimeoutException。
您可以查看 ExpectedCondition here 的 API(您可以在此类中使用许多有趣的变体)
(注意驱动程序只有在找不到你的代码正在寻找的元素时才会等待指定的时间段,如果驱动程序找到了一个元素,它就会继续执行)