Selenium automatically accepting alerts(Selenium 自动接受警报)
问题描述
有谁知道如何禁用它?或者如何从已自动接受的警报中获取文本?
Does anyone know how to disable this? Or how to get the text from alerts that have been automatically accepted?
这段代码需要工作,
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
我正在使用带有 Selenium 2.32 的 FF 20
I am using FF 20 with Selenium 2.32
推荐答案
就在前几天我回答了类似的问题,所以它仍然很新鲜.您的代码失败的原因是,如果在处理代码时未显示警报,它将大部分失败.
Just the other day i've answered something similar to this so it's still fresh. The reason your code is failing is if the alert is not shown by the time the code is processed it will mostly fail.
谢天谢地,来自 Selenium WebDriver 的人已经为它实现了等待.因为你的代码就这么简单:
Thankfully, the guys from Selenium WebDriver have a wait already implemented for it. For your code is as simple as doing this:
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
这里,如果你想要这个方法背后的代码这里.
You can find all the API from ExpectedConditions
here, and if you want the code behind this method here.
这段代码也解决了这个问题,因为关闭警报后无法返回alert.getText(),所以我为你存储在一个变量中.
This code also solves the problem because you can't return alert.getText() after closing the alert, so i store in a variable for you.
这篇关于Selenium 自动接受警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Selenium 自动接受警报
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01