java - 如何使用 Selenium 在 chrome 中获取警报框

标签 java selenium google-chrome

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/

相关文章:

java - 如何在jtextbox上实时验证正则表达式?

java - 如何在 Eclipse 中设置自动类路径更新?

java - 无法在 Appium 中执行点击或发送键

python - Selenium 嵌套选择器无法按预期工作

html - 用于 Google Chrome 的类似 Firebug 的调试器

html - 如何修复无法在Android上正确显示的网页(可能是CSS问题-使用Bootstrap)

java - 如何在非二叉树的一次递归搜索中获取节点的深度

css - 使用 CSS 选择器访问带有 selenium 的特定表行

javascript - html 音频元素的自定义起点和终点

java - Spring Boot JPA CrudRepository - 实体不附加到 persistencecontext