Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

selenium - Handle windows authentication pop up on Chrome

I am trying to handle the basic authentication pop up for my Selenium webdriver scripts using AutoIt. I wrote a script for Firefox and Internet Explorer but it doesn't work for Chrome.

When I tried identifying the authentication pop up on Chrome using AutoIt Window Information Tool it came up empty. I am using following AutoIt script:

WinWaitActive("Authentication Required","","120")
If WinExists("Authentication Required") Then
    Send("username{TAB}")
    Send("password{Enter}")
EndIf

Any pointers to get this to work would be helpful. I am not using username@password:google.com because some authentication pop ups appear on redirection.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all you don't need AutoIt, you can just use the windows API. Secondly, Chrome's basic authentication dialog is not a traditional Window, so you can't get a handle to it (Try using Spy++). The only reason this would work is if you didn't bring another window to the foreground prior to the SendKeys call. You need to find the parent Chrome window, which may be something like "URL - Google Chrome", move it to the front and then send keys. Here's an example:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr point);

[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string className, string windowTitle);

public static void SendBasicAuthentication(string username, string password, string windowTitle)
{
    var hwnd = FindWindow(null, windowTitle);
    if (hwnd.ToInt32() <= 0 || !SetForegroundWindow(hwnd)) return;
    SendKeys.SendWait(username.EscapeStringForSendKeys());
    SendKeys.SendWait("{TAB}");
    SendKeys.SendWait(password.EscapeStringForSendKeys());
    SendKeys.SendWait("{ENTER}");
}

static string EscapeStringForSendKeys(this string input)
{
    // https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx
    // must do braces first
    return input.Replace("{", "{{}")
        .Replace("}", "{}}")
        .Replace("^", "{^}")
        .Replace("%", "{%}")
        .Replace("~", "{~}")
        .Replace("(", "{(}")
        .Replace(")", "{)}")
        .Replace("[", "{[}")
        .Replace("]", "{]}");
}

Hope that helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...