sta*_*low 62 java selenium-webdriver
我正在尝试使用Java和Selenium WebDriver自动化一些测试用例.我有以下场景:
关闭弹出窗口后,我需要点击同一页面中的"添加项目"按钮.但是当WebDriver试图找到"添加项目"按钮时,如果互联网速度太快,WebDriver可以找到并单击该元素.
但是如果互联网很慢,WebDriver会在页面刷新之前找到按钮,但只要WebDriver单击该按钮,页面就会刷新并StaleElementReferenceException
发生.
StaleElementReferenceException
发生之前.如果Thread.sleep(3000);
在单击"添加项目"按钮之前使用测试用例,则工作正常.这个问题还有其他解决方法吗?
Kim*_*ann 76
3个答案,你可以结合:
1.)在创建Web驱动程序实例后立即设置隐式等待:_ = driver.Manage().Timeouts().ImplicitWait;
.这将尝试等到页面在每个页面导航或页面重新加载时完全加载.
2.)页面导航后,调用JavaScript return document.readyState
直到"complete"
返回.Web驱动程序实例可以充当JavaScript执行程序.示例代码:
C#
new WebDriverWait(driver, MyDefaultTimeout).Until(
d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
Run Code Online (Sandbox Code Playgroud)
Java的
new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Run Code Online (Sandbox Code Playgroud)
3.)在2.)之后,检查URL是否与您期望的模式匹配.
Flo*_* B. 14
在点击"添加"按钮之前,您似乎需要等待重新加载页面.在这种情况下,您可以在单击重新加载的元素之前等待"Add Item"元素变为陈旧:
WebDriverWait wait = new WebDriverWait(driver, 20);
By addItem = By.xpath("//input[.='Add Item']");
// get the "Add Item" element
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));
//trigger the reaload of the page
driver.findElement(By.id("...")).click();
// wait the element "Add Item" to become stale
wait.until(ExpectedConditions.stalenessOf(element));
// click on "Add Item" once the page is reloaded
wait.until(ExpectedConditions.presenceOfElementLocated(addItem)).click();
Run Code Online (Sandbox Code Playgroud)
在单击添加项目之前,您可以通过多种方式执行此操作:
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid")));// instead of id u can use cssSelector or xpath of ur element.
or
wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));
Run Code Online (Sandbox Code Playgroud)
你也可以这样等 如果您想等到上一页元素不可见:
wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));
Run Code Online (Sandbox Code Playgroud)
这里是你找到所有可用于等待及其文档的selenium webdriver api的链接.