如何处理硒中的"需要身份验证"弹出窗口

suc*_*tag 6 authentication selenium selenium-webdriver

是否可以在selenium中处理"需要身份验证"弹出窗口,其中包含使用Alert的"UserName"和"Password"字段.

在此输入图像描述

San*_*ani 0

您可以检查警报弹出窗口。为此,您需要导入以下内容,

import org.openqa.selenium.security.UserAndPassword;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
Run Code Online (Sandbox Code Playgroud)

首先,您需要等到弹出窗口出现。

WebDriverWait wait = new WebDriverWait(driver, 30);
Run Code Online (Sandbox Code Playgroud)

然后检查警报弹出窗口是否存在/可见

Alert alertPopUp = wait.until(ExpectedConditions.alertIsPresent()); 
Run Code Online (Sandbox Code Playgroud)

然后你可以使用selenium web驱动程序的authenticateUsing方法。

alertPopUp.authenticateUsing(new UserAndPassword("your_username", "your_password"));
Run Code Online (Sandbox Code Playgroud)

如果您只想验证警报的存在,还有另一种快速检查的方法

try {
  Alert alert = driver.switchTo().alert();
  alert.accept();

 } catch (NoAlertPresentException e) {
   // Alert not available
   e.printStackTrace();
 }
Run Code Online (Sandbox Code Playgroud)