【问题标题】:How to get Alert Box in chrome using Selenium如何使用 Selenium 在 chrome 中获取警报框
【发布时间】:2020-01-16 14:43:48
【问题描述】:
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 延迟该过程,但仍然无法正常工作。

【问题讨论】:

    标签: java selenium google-chrome


    【解决方案1】:

    您可以在新的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 元素来验证这一点。

    【讨论】:

      【解决方案2】:

      您可以使用显式等待,直到警报出现后再切换到它。试试下面的代码

      new WebDriverWait(driver, 40)
              .ignoring(NoAlertPresentException.class)
              .until(ExpectedConditions.alertIsPresent());
      
      Alert al = driver.switchTo().alert();
      
      String msg = al.getText();
      

      【讨论】:

      • 您确定是提示框(网页提示或窗口提示)还是弹出框?
      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多