如何在 Selenium Webdriver 中捕获警报消息中的文本?

seleniumautomation testingtesting tools

我们可以借助 Alert 接口捕获 Selenium Webdriver 中警报消息中的文本。默认情况下,Webdriver 对象控制着主页面,一旦生成警报弹窗,我们就必须将 Webdriver 焦点从主页面转移到警报上。

这可以通过 switchTo().alert() 方法完成。一旦驱动程序焦点转移,我们就可以借助 switchTo().alert().getText() 方法获取弹窗的文本。最后,我们将使用 accept 方法接受警报,并使用 dismiss 方法将其关闭。

让我们以下面的警报为例,获取其消息 −

语法

Alert a = driver.switchTo().alert();
String s= driver.switchTo().alert().getText();
a.accept();

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class JsEnterText{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //隐式等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL 启动
      driver.get("https://the-internet.herokuapp.com/javascript_alerts");
      // 识别元素
      WebElement l = driver.
      findElement(By.xpath("//*[text()='Click for JS Alert']"));
      l.click();
      // 将焦点切换到警报
      Alert a = driver.switchTo().alert();
      // 获取警报文本
      String s= driver.switchTo().alert().getText();
      System.out.println(&" 警报文本为: &" + s);
      // 接受警报
      a.accept();
      driver.quit();
   }
}

输出


相关文章