在Chrome上弹出处理窗口身份验证

时间:2013-10-14 09:54:45

标签: selenium selenium-webdriver webdriver autoit

我正在尝试使用AutoIt处理我的Selenium webdriver脚本的基本身份验证。我为Firefox和Internet Explorer编写了一个脚本,但它不适用于Chrome。

当我尝试使用AutoIt Window Information Tool在Chrome上识别身份验证时,它显示为空。我正在使用以下AutoIt脚本:

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

任何能够让它发挥作用的指针都会有所帮助。我没有使用username@password:google.com,因为重定向会出现一些身份验证弹出窗口。

4 个答案:

答案 0 :(得分:3)

我能够让AutoIt按文字定位窗口,而不是窗口标题。 AutoIt窗口信息工具无法识别标题,但它确实识别了可见文本。

所以我将脚本更改为:

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

工作正常。

答案 1 :(得分:2)

首先,您不需要AutoIt,您只需使用Windows API即可。其次,Chrome的基本身份验证对话框不是传统的Window,因此您无法获得它(尝试使用Spy ++)。这可行的唯一原因是如果在SendKeys调用之前没有将另一个窗口带到前台。您需要找到父Chrome窗口,可能是“ URL - Google Chrome”,将其移到前面然后发送密钥。这是一个例子:

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("]", "{]}");
}

希望有所帮助。

答案 2 :(得分:0)

我使用了你的脚本并根据我的需要扩展了一点。用户和密码不是硬编码的,可以通过命令行或用户输入进行设置。该脚本只需启动一次。

If(Not IsArray($CmdLine) Or $CmdLine[0] < 2) Then
   $user = InputBox ("User", "Please enter your user", "")
   $pass = InputBox ("Password", "Please enter your password", "", "*M")
Else
   $user = $CmdLine[1]
   $pass = $CmdLine[2]
EndIf


While(True)
   WinWaitActive("", "Authentifizierung erforderlich","120")
   If WinExists("", "Authentifizierung erforderlich") Then
      Send($user)
      Send("{TAB}")
      Send($pass)
      Send("{Enter}")
      Sleep(1000)
   EndIf
WEnd

下一步是找出chrome中设置的语言,并根据它设置窗口标题。

答案 3 :(得分:0)

请尝试一下,我的正在工作,我从nuget获得了AutoItX:

AutoItX.WinWait("title of your browser", "", 9); 
AutoItX.WinActivate("title of your browser");
AutoItX.Send("userid");
AutoItX.Send("{TAB}", 0);
AutoItX.Send("password");
AutoItX.Send("{Enter}", 0);
相关问题