如何使用Firefox驱动程序读取警报消息?

Sap*_*pna 3 selenium selenium-firefoxdriver selenium-webdriver

我需要使用java读取弹出窗口中显示的警报和确认消息,并在控制台上打印.在从IDE导出selenium记录作为Junit4(WebDriver)java文件时,我的代码是:

private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();

@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
}
Run Code Online (Sandbox Code Playgroud)

现在当我尝试使用getAlertgetConfirmation功能如下所示:

@Test
public void testSample() throws Exception {
Alert alert = driver.switchTo().alert();
message = alert.getText();
System.out.println("message is "+message);
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

java.lang.NullPointerException
at com.example.tests.Sample.testSample(Sample.java:40)
at com.example.tests.Sample.main(Sample.java:149)
Exception: null
Run Code Online (Sandbox Code Playgroud)

我该如何处理?还有其他方法来阅读弹出消息吗?

Har*_*ddy 5

在testSample()方法中导航到任何页面时使用 -

driver.get("URL");
Run Code Online (Sandbox Code Playgroud)

之后,您可以解释警报消息如何在第一位出现.

你确定出现的弹出消息是一个javascript alert或任何打开的窗口.

如果是警报消息,则可以使用以下方式访问它:

driver.switchTo().alert();
Run Code Online (Sandbox Code Playgroud)

但如果弹出窗口是另一个窗口,那么你将不得不使用 -

driver.switchTo().window("windowName");
Run Code Online (Sandbox Code Playgroud)

您可以从此处获得有关此内容的更多信息.