gpt4 book ai didi

java - Selenium 自动接受警报

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:57 24 4
gpt4 key购买 nike

有谁知道如何禁用它?或者如何从已自动接受的警报中获取文本?

这段代码需要工作,

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 here 中找到所有 API , 如果你想要这个方法背后的代码 here .

这段代码也解决了这个问题,因为你不能在关闭警报后返回 alert.getText(),所以我为你存储在一个变量中。

关于java - Selenium 自动接受警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16448173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com