Selenium自动接受警报
有谁知道如何禁用它? 或者如何从已自动接受的警报中获取文本?
这段代码需要工作,
driver.findElement(By.xpath("//button[text() = \"Edit\"]")).click();//causes page to alert() something Alert alert = driver.switchTo().alert(); alert.accept(); return alert.getText();
但反而给出了这个错误
No alert is present (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 2.14 seconds
我正在使用FF 20和Selenium 2.32
就在前几天,我已经回答了类似的事情,所以它仍然很新鲜。 您的代码失败的原因是,如果在处理代码时未显示警报,则它将大部分失败。
值得庆幸的是 ,来自Selenium WebDriver的人已经等待它了。 对于您的代码就像这样简单:
String alertText = ""; WebDriverWait wait = new WebDriverWait(driver, 5); // This will wait for a maximum of 5 seconds, everytime wait is used driver.findElement(By.xpath("//button[text() = \"Edit\"]")).click();//causes page to alert() something wait.until(ExpectedConditions.alertIsPresent()); // Before you try to switch to the so given alert, he needs to be present. Alert alert = driver.switchTo().alert(); alertText = alert.getText(); alert.accept(); return alertText;
你可以在这里找到ExpectedConditions
所有API,如果你想在这里找到这个方法背后的代码。
此代码也解决了这个问题,因为您在关闭警报后无法返回alert.getText(),因此我会为您存储一个变量。
在接受()之前,您需要获取文本的警报。 你现在正在做的是在警报上接受(点击“确定”), 然后尝试在警报文本离开屏幕后获取警报文本,即没有警报。
尝试以下操作,我刚刚添加了一个String,用于检索警报文本,然后返回该字符串。
driver.findElement(By.xpath("//button[text() = \"Edit\"]")).click();//causes page to Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); alert.accept(); return alertText;
Selenium webdriver不会wait
警报。 因此它会尝试切换到不存在的警报,这就是它失败的原因。
为了快速而不那么好的修复,请进入sleep
。
在尝试切换到警报之前,更好的解决方案是实现自己的等待警报方法。
UPDATE
像这样的东西,从这里复制粘贴
waitForAlert(WebDriver driver) { int i=0; while(i++<5) { try { Alert alert3 = driver.switchTo().alert(); break; } catch(NoAlertPresentException e) { Thread.sleep(1000) continue; } } }
使用synchronized选项的以下方法将增加更多稳定性
protected Alert getAlert(long wait) throws InterruptedException { WebDriverWait waitTime = new WebDriverWait(driver, wait); try { synchronized(waitTime) { Alert alert = driver.switchTo().alert(); // if present consume the alert alert.accept(); return alert; } } catch (NoAlertPresentException ex) { // Alert not present return null; } }