我正在尝试使用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
,因为重定向时会出现一些身份验证弹出窗口。 最佳答案
首先,您不需要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("]", "{]}");
}
希望能有所帮助。