Selenium浏览器usernamd和密码弹出窗口 - 无法处理(Java)

时间:2018-02-07 20:30:24

标签: java selenium selenium-webdriver

登录脚本出现问题。 用户导航到siteA。此时输入并通过电子邮件发送地址并单击按钮。然后将用户重定向到siteB,其中显示用户名和密码的浏览器验证窗口。输入后,用户将重定向回siteA。

我想,这应该很容易做到。但是,当我遇到浏览器身份验证弹出窗口时,我无法切换到它。我也看到旧的UserAndPassword导入不再起作用了(我使用的是3.9.0)

这是我的代码:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Login {

    public static void main(String[] args) {

        String url      = "url";
        String username = "username";
        String password = "password";

        System.setProperty("webdriver.gecko.driver","resources/GeckoDriver/v0.19.1-win64/geckodriver.exe");
        WebDriver driver = new FirefoxDriver();

        // open the browser and navigate to the url
        driver.get(url);

        // set some window size and timeouts
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        // enter text
        driver.findElement(By.name("loginfmt")).sendKeys("emailAdd");

        // click login button
        driver.findElement(By.id("idSIButton9")).click();

        Alert windowAlert = driver.switchTo().alert();

        UserAndPassword uAp = new UserAndPassword(username, password);

        windowAlert.authenticateUsing(uAp);

        driver.switchTo().defaultContent();     

    }

}

我认为用户名和密码的内容存储在导入org.openqa.selenium.security。*但无法得到。这被移动了吗?

1 个答案:

答案 0 :(得分:0)

你可以进行某种锻炼。您不会显式调用单击按钮,而是获取其重定向属性,使用WebDriver的get()方法并通过它进行身份验证。

WebElement redirectionButton = driver.findElement(By.id("idSIButton9"));
String redirectionURL = redirectionButton.getAttribute("href"); //this part might be tricky. Href can be relative or absolute path. If it's relative, add current url to it
//optional, depends on href:
redirectionURL = driver.getCurrentUrl() + redirectionURL;

//now, since we have URL for the desired page, instead of clicking the button we will open the page.
driver.get("https://" + username + ":" + password + "@" + redirectionURL);