Selenium WebDriver with automated Basic Auth credentials
Selenium is a marvelous library for automating browsers. Perl has an interface via Selenium::Remote::Driver. A short script looks like:
use Selenium::Remote::Driver;
my $driver = new Selenium::Remote::Driver;
$driver->get(‘http://www.google.com’);
print $driver->get_title();
$driver->quit();
Under the assumption that a selenium server is found, this will launch google and print the title. It works very well for a lot of scenarios. One scenario where it has trouble is with Basic Auth and credentials. The browser usually outputs a popup requiring user-input.
This user-input can be automated via OS specific libraries. Under Windows and ActiveState the PerlScript (one word) interface can be utilized to realize a credential entry system.
The code below will launch a browser and then input the credentials for http://test.webdav.org/auth-basic. It has been tested on Windows 7, Firefox, Selenium WebDriver 2.0.25, and ActiveState 5.14.2.
use Selenium::Remote::Driver;
use Win32::Process;
use Win32;
$WshArgs = $WScript->{Arguments};
my $password = $WshArgs->Item(0);
if ($password) {
$WshShell = $WScript->CreateObject(“WScript.Shell”);
while (1) {
if ($WshShell->AppActivate(“Authentication Required”)) {
$WshShell->SendKeys(“user1”);
$WshShell->SendKeys(“{TAB}”);
$WScript->Sleep(100);
$WshShell->SendKeys(“user1”);
$WScript->Sleep(100);
$WshShell->SendKeys(“{ENTER}”);
exit;
}
select(undef, undef, undef, 0.3);
}
exit;
}
sub ErrorReport{
$WScript->Echo(Win32::FormatMessage( Win32::GetLastError() ));
}
my $driver = Selenium::Remote::Driver->new();
my $ProcessObj;
Win32::Process::Create($ProcessObj,
“c:\windows\system32\cmd.exe”,
“start cmd /k cscript keystrokes.pls -password”,
0,
NORMAL_PRIORITY_CLASS | DETACHED_PROCESS,
“.”) || die ErrorReport();
$driver->get(‘http://test.webdav.org/auth-basic’);
$ProcessObj->Kill(0);
$WScript->Echo($driver->get_title());
$driver->quit();