5

我有一个网站,其中大多数页面通常通过 HTTP 使用,但其他一些页面只能通过 HTTPS 使用。站点受基本身份验证保护(HTTP 和 HTTPS 页面的凭据相同)。

当我在浏览器(FF 或 Chrome)中打开任何 HTTP 页面并单击指向 HTTPS 页面的链接时,浏览器会显示要求基本身份验证凭据的警报。

我对 Webdriver(FF 或 Chrome)有同样的问题:
当我访问http://username:password@some_domain.com并单击指向 HTTPS 页面的链接时,会出现要求基本身份验证凭据的浏览器警报窗口。Selenium 不会“记住”为 HTTP 页面输入的凭据。

如何使用 Webdriver 遵循这一系列操作?如果不可能,你有什么建议?

4

2 回答 2

3
 FirefoxProfile profile = new FirefoxProfile();
 profile.SetPreference("network.http.phishy-userpass-length", 255);
 profile.SetPreference("network.automatic-ntlm-auth.trusted-uris", hostname);
 Driver = new FirefoxDriver(profile);

主机名是您的 URL (example.com) 然后尝试

Driver.Navigate().GoToUrl(http://user:password@example.com);
于 2013-06-03T15:58:41.410 回答
1

到目前为止,我能够提出的最佳解决方案是创建一个处理超时的新线程。由于 WebDriver 不会返回对 FF 和其他某些浏览器的控制,我可以调用线程处理程序,然后使用 Robot 输入凭据并按 Enter(也可以在此处使用 AutoIt)。然后将控件返回给 WebDriver 以继续执行脚本。

//put this where it belongs, say calling a new url, or clicking a link 
//assuming necessary imports 

int pageLoadTimeout = 10;
String basicAuthUser = "user";
String basicAuthPass = "pass";
String url = "https://yourdomain.com";

WebDriver driver = new FirefoxDriver();

TimeoutThread timeoutThread = new TimeoutThread(pageLoadTimeout);
timeoutThread.start();

driver.get(url);

//if we return from driver.get() call and timeout actually occured, wait for hanlder to complete
if (timeoutThread.timeoutOccurred){
    while (!timeoutThread.completed) 
        Thread.sleep(200);
}
else {
    //else cancel the timeout thread
    timeoutThread.interrupt();
}


public class TimeoutThread extends Thread {

    int timeout;
    boolean timeoutOccurred;
    boolean completed;

    public TimeoutThread(int seconds) {
        this.timeout = seconds;
        this.completed = false;
        this.timeoutOccurred = false;
    }

    public void run() {
        try {

            Thread.sleep(timeout * 1000);
            this.timeoutOccurred = true;
            this.handleTimeout();
            this.completed = true;

        } 
        catch (InterruptedException e) {
            return;
        }
        catch (Exception e){
            System.out.println("Exception on TimeoutThread.run(): "+e.getMessage());
        }
    }

    public void handleTimeout(){

        System.out.println("Typing in user/pass for basic auth prompt");

        try {
            Robot robot = new Robot();

            //type is defined elsewhere - not illustrating for this example 
            type(basicAuthUser); 
            Thread.sleep(500);

            robot.keyPress(KeyEvent.VK_TAB);
            robot.keyRelease(KeyEvent.VK_TAB);
            Thread.sleep(500);

            type(basicAuthPass);
            Thread.sleep(500);

            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);
        }
        catch (AWTException e) {
            System.out.println("Failed to type keys: "+e.getMessage());
        }
    }
}
于 2013-08-02T20:04:15.727 回答