Java Selenium - 无法同时使用 Chrome 和 firefox 到达警报

Java Selenium - Unable to reach to Alert with both Chrome and firefox

我是 Selenium 的新手,我编写了以下代码来打印警报文本并接受警报。

public class AlertPractice {

 public static void main(String[] args) throws InterruptedException {

    WebDriver driver  = new FirefoxDriver();
    driver.get("http://output.jsbin.com/usidix/1");

    driver.findElement(By.cssSelector("input[value=\"Go!\"]")).click();
    Thread.sleep(1000);
    String S = driver.switchTo().alert().getText();
    Thread.sleep(1000);
    driver.switchTo().alert().accept();

    System.out.println(S);
    driver.close();
}

在 运行 FIREFOX 驱动程序 我得到以下异常:

org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output....

和 运行 Chrome 驱动程序 我遇到以下异常:

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot determine loading status from unexpected alert open (Session info: chrome=53.0.2785.101) (Driver info: chromedriver=2.21.371459 ...

任何帮助将不胜感激。

要发布最新的Mozilla Firefox, you need to download latest geckodriver executable and then

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot determine loading status from unexpected alert open

其实不需要切换Alert两次来获取提示文本然后接受。您可以使用一次切换到 Alert.

来完成这两项任务

为了更好的方法,您应该尝试使用 WebDriverWait 切换 Alert 以等待警报出现,而不是 Thread.sleep(),如下所示:-

driver.findElement(By.cssSelector("input[value='Go!']")).click();

WebDriverWait wait = WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());

String S = alert.getText();
System.out.println(S);

alert.accept();

Selenium 的 Webdriver 版本对于 Firefox 和 Chrome驱动程序版本对于 Chrome 似乎是一个问题。下载并应用了 selenium 的最新测试版和 chrome 的最新 chrome 驱动程序。现在工作正常。