这个问题与下面的问题类似:
即如何等到进度条消失。
How to wait dynamically until the progress bar to load completely in Selenium Webdriver?
我的情况有点不同。在我的场景中,当进度条出现时,所有元素都被禁用。我正在使用显式等待,但仍然出现异常。
场景:
在注册页面中提供所有详细信息后,脚本会单击“创建帐户”按钮。此时会出现一个圆形的进度条,并持续1、2秒。如果输入的密码无效,错误消息将显示在注册页面的顶部。我现在需要单击“取消”按钮并重复该过程。
当进度条出现时,整个页面被禁用。只有在进度条消失后,用户才能继续。
这是我的代码:
WebDriverWait myWaitVar = new WebDriverWait(driver,20);
单击“创建帐户”按钮后,将显示进度条。代码现在应该等到“取消”按钮出现。
//Click on the "Create Account" button.
driver.findElement(By.id("createAccount")).click();
//Wait till the "Cancel" button shows up -- this may take some time.
myWaitVar.until(ExpectedConditions.elementToBeClickable (By.id("cancelRegister")));
//Click on the "Cancel" button.
driver.findElement(By.id("cancelRegister")).click();
当我执行上面的代码时,我总是在最后一行得到 NoSuchElementException
。
我尝试使用 ExpectedCondition.visibilityOfElement()
但这也会产生 NoSuchElementException
。
我让它工作的唯一方法是强制它 hibernate :
Thread.sleep(3000);
脚本在 sleep 时运行良好。
为什么 WebDriverWait
不等到进度条消失?该代码成功解析了 elementToBeClickable()
,但在单击“取消”按钮时它总是抛出异常。
最佳答案
ExpectedConditions.elementToBeClickable
如果条件为真,则返回元素意味着如果元素出现在页面上并且可点击,则返回元素,无需再次找到该元素,只需省略最后一行,如下所示:-
//Click on Create Account btn:
driver.findElement(By.id("createAccount")).click();
//Wait till "Cancel" button is showing up. At cases, it may take some time.
WebElement el = myWaitVar.until(ExpectedConditions.elementToBeClickable(By.id("cancelRegister")));
el.click();
Edited1 :- 如果由于其他元素收到点击而无法点击,您可以使用 JavascriptExecutor
执行点击,如下所示:
//Click on Create Account btn:
driver.findElement(By.id("createAccount")).click();
//Wait till "Cancel" button is showing up. At cases, it may take some time.
WebElement el = myWaitVar.until(ExpectedConditions.elementToBeClickable(By.id("cancelRegister")));
((JavascriptExecutor)driver).executeScript("arguments[0].click()", el);
Edited2 :- 从提供的异常看来,进度条仍然覆盖在 cancelRegister
按钮上。所以最好的方法是先等待进度条不可见,然后等待 cancelRegister
按钮可见,如下所示:
//Click on Create Account btn:
driver.findElement(By.id("createAccount")).click();
//Now wait for invisibility of progress bar first
myWaitVar.until(ExpectedConditions.invisibilityOfElementLocated(By.id("page_loader")));
//Now wait till "Cancel" button is showing up. At cases, it may take some time.
WebElement el = myWaitVar.until(ExpectedConditions.elementToBeClickable(By.id("cancelRegister")));
el.click();
希望它有用...:)
关于java - 在 Selenium Webdriver 中,ExpectedCondition.elementToBeClickable 不会等到进度条消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38673465/