如何处理“意外警报打开”?

由于弹出窗口,我遇到了Selenium抛出timeout exception的问题

  unexpected alert open not provide any stacktrace information) Command duration or timeout: 5 milliseconds 

警报有OKCANCEL按钮。 我知道有两种方法来处理这个问题


第一种方法是重新打开一个新会话

 driver.quit(); driver = new ChromeDriver(); 

第二种方式是使用Robot类

 Robot r = new Robot(); r.keyPress(KeyEvent.VK_ENTER); r.keyRelease(KeyEvent.VK_ENTER); 

但是,这种方法不具有时间效率。 有没有更好的方法?

这应该是诀窍:

 driver.switchTo().alert().accept(); 

如果出现,您可以默认将chrome function设置为ACCEPTINGOREDISMISS警报。

例:

 capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT); 

尝试这个,

 public boolean isAlertPresent() { boolean presentFlag = false; try { // Check the presence of alert Alert alert = driver.switchTo().alert(); // Alert present; set the flag presentFlag = true; // if present consume the alert alert.accept(); //( Now, click on ok or cancel button ) } catch (NoAlertPresentException ex) { // Alert not present ex.printStackTrace(); } return presentFlag; } 

我希望这对你有所帮助。

更常见的是,这个问题很麻烦,因为它出现在被测系统中不可预测的地方。 现在,我不认为存在通过webdriver中的配置自动处理所有这些不可用性的方法。 我的一般建议是将webDriver包装在Proxy中,并使用某种动态代理来包装所有webdriver方法。 通过这种方式,您可以对不可预测的警报进行单点控制,获取记录或评估方法性能,处理随机unreachableBrowserexception,处理随机StaleElementException等。我发现这对于各种情况非常有用,性能损失很小。

  Class WebDriverProxy implements InvocationHandler{ WebDriverWrapperImpl impl = new WebDriverWrapperImpl(); public String clickByXPath(String xpath) { return (String)handleInvocation(impl,"clickByXPath", new Object[]{xpath}); // return impl.clickByXPath( xpath) ; } /**All fail fast strategies could be centralized here., no need of any assertion errors in libraries, * However it makes sense to wrap webdriver exceptions as either recoverable or nonrecoverable * recoverable ones are like unexpected hangs on the browser, which could be handled at the test runner level, wherein the * whole test can be retried. * irrecoverable ones are also mostly handled at the test runner level, but capable of being caught at the test script level * **/ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object o = null; Throwable target = null; try{ o = method.invoke(proxy, args); } catch(InvocationTargetException ee){ target = ee.getTargetException(); throw target; } return o; } public Object handleInvocation(Object proxy, String method, Object[] args){ Object toReturn = null; Method m = null; Class[] classes = new Class[args.length]; for(int i = 0;i 

如果你正在使用像TestNG这样的任何框架,你可以使用像ITestListener等监听器,你必须覆盖一些方法,如BeforeCommand和afterCommand。 因此在BeforeCommand中,实现警报代码以解除并检查美观。 当执行selenium命令时,此beforeCommand方法将自动调用并检查是否存在警报。 如果是,它将解除并执行您的命令。 我希望它能解决你的问题