package com.company;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.json.JsonOutput;
import java.io.IOException;
import java.security.Key;
import java.sql.SQLOutput;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Logan\\Downloads\\selenium-java-3.141.59\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
Alert alert = driver.switchTo().alert();
String msg = alert.getText();
我想在窗口打开时收到警报框。我尝试使用 Thread.sleep 延迟该过程,但仍然不起作用。
最佳答案
您可以在新的 ExpectedConditions.alertIsPresent()
上调用 WebDriverWait
,而不是 thread.sleep()
,以确保警报完全加载在尝试调用 alert.getText()
之前:
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
// add the above import statements
// wait for alert to exist
new WebDriverWait(driver, 30).until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
String msg = alert.getText();
如果这对您不起作用,您的浏览器可能不会显示真正的警报 - 您可以尝试检查弹出窗口并查看其后面是否有任何 HTML 元素来验证这一点。
关于java - 如何使用 Selenium 在 chrome 中获取警报框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59772058/