I have written several Selenium Website Tests, however, this is my first with a site that is set to Windows Authentication.
I have been trying with Chrome and IE.
With IE I can successfully login to the site, and I see AutoIt typing and I can see that the browser successfully loads the correct page after login, however, the driver never has a connection to that browser.
With Chrome, I can never find the window to connect with AutoIt.
Using C#. See inline code comments for more specifics on the errors.
try
{
var autoIT = new AutoItX3();
if (IE) //IE Driver - Driver looses connection with the window immediately on Navigate, but AutoIT login works.
//(Driver does work fine if I go to a non-windows authentication site)
{
driver.Navigate().GoToUrl(testConfig.Url);
System.Threading.Thread.Sleep(2000);
//driver.CurrentWindowHandle crashes, 'No Window Exits'
var driverHandles = driver.WindowHandles; //result is 0
var test4 = autoIT.WinActive("Windows Security");
autoIT.WinActivate("Windows Security");
autoIT.Send("zzzzzzz");//Don't need user as it remembers
System.Threading.Thread.Sleep(1000);
autoIT.Send("{TAB}");
autoIT.Send("{ENTER}");
//Visually I can see Browser is logged in and full page loads.
autoIT.WinActivate("EDB Data Manager - Internet Explorer");
var test5 = autoIT.WinGetTitle("EDB Data Manager - Internet Explorer");
System.Threading.Thread.Sleep(2000);
driver.Url = testConfig.Url;
System.Threading.Thread.Sleep(2000);
var driverHandles2 = driver.WindowHandles; //result is still 0
//this will fail
IWebElement userName = driver.FindElement(By.Id("WellsCard"));
//I've tried refreshing or navigating to the url again with no success.
}
else //chrome Driver Driver maintains connection with the window immediately, but AutoIT fails, as I can't find window.
{
driver.Navigate().GoToUrl(testConfig.Url);
System.Threading.Thread.Sleep(2000);
var test7 = autoIT.WinExists("Authentication Required");
var tes8 = autoIT.WinExists("data:, - Google Chrome");
var test9 = autoIT.WinExists("EDB Data Manager - Internet Explorer");
var test10 = autoIT.WinExists("Untitled - Google Chrome");
//None exist, so this will not work.
autoIT.WinActivate("Authentication Required");
autoIT.Send("myUserName");
autoIT.Send("{TAB}");
autoIT.Send("zzzzz");
System.Threading.Thread.Sleep(1000);
autoIT.Send("{TAB}");
autoIT.Send("{ENTER}");
}
}
catch (Exception ex)
{
output.OutputMessage(ex.ToString());
}
Related
I am working on a C# project where I am trying to send a excel file by WhatsApp. The problem is that whenever I run the code a new instance of command window is open, and a new window is opened for chrome every time I ran the code. Before running the code, I have already log-in to my WhatsApp account and wants to use the same window and tab to avoid logging each time. I have tried to use several ways to stop this but failed to achieve the result. Please correct the code. Please don't mind my bad English.
var options = new ChromeOptions();
options.AddArguments(#"user-data-dir=C:\Users\Umesh Aggarwal\AppData\Local\Google\Chrome\User Data");
IWebDriver driver = new ChromeDriver(#"C:\Users\Umesh Aggarwal\Desktop\chromedriver_win32", options);
////// Navigate to Whatsapp web
driver.Navigate().GoToUrl("https://web.whatsapp.com/");
IReadOnlyCollection<string> windowHandles = driver.WindowHandles;
// Find already opened window with Chrome
string chromeWindow = "";
foreach (string window in windowHandles)
{
driver.SwitchTo().Window(window);
if (driver.Title.Contains("Google Chrome"))
{
chromeWindow = window;
break;
}
}
// Switch to Chrome window
driver.SwitchTo().Window(chromeWindow);
// Get all open tabs in Chrome window
IReadOnlyCollection<string> tabHandles = driver.WindowHandles;
// Find already opened tab of Whatsapp web
string whatsappTab = "";
foreach (string tab in tabHandles)
{
driver.SwitchTo().Window(tab);
if (driver.Title.Contains("Whatsapp"))
{
whatsappTab = tab;
break;
}
}
//// Switch to Whatsapp tab
driver.SwitchTo().Window(whatsappTab);
The problem is that I need to get the PID of IE browser instances so that I can close the IE browser(Working in C#).
I launched the IE browser using Selenium and then used Driver Service class as :-
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService();
Console.WriteLine(driverdetails.Port);
The plan is to get the port and then have its child process. I am able to do so using a debugger by entering the value of Port manually. But, the port fetched by driverdetails.Port was not the actual port used by my driver.
Is there any was, I can find the Port for any given driver service?
For IE i have an alternative to launch IE and get the URL with port which says http://localhost:. However, this is not the case with other browsers. My want is to make the generic code and hence I am using the Driver Service object.
As far as I know, the InternetExplorerDriverService's ProcessID property gets the process ID of the running driver service executable, and we can't get the IE browser instance PID through the InternetExplorer webdriver. If you want to get the PID, you could try to use the Process class.
From your description, it seems that you want to close the IE tab or window by using the IE Webdriver. If that is the case, I suggest you could use InternetExplorerDriver WindowHandles to get the opened windows, then use the switchto method to switch the window and check the url or title, finally, call the Close method to close the IE window. Please refer to the following sample code:
private const string URL = #"https://dillion132.github.io/login.html";
private const string IE_DRIVER_PATH = #"D:\Downloads\webdriver\IEDriverServer_x64_3.14.0"; // where the Selenium IE webdriver EXE is.
static void Main(string[] args)
{
InternetExplorerOptions opts2 = new InternetExplorerOptions() { InitialBrowserUrl = "https://www.bing.com", IntroduceInstabilityByIgnoringProtectedModeSettings = true, IgnoreZoomLevel = true };
using (var driver = new InternetExplorerDriver(IE_DRIVER_PATH, opts2))
{
driver.Navigate();
Thread.Sleep(5000);
//execute javascript script
var element = driver.FindElementById("sb_form_q");
var script = "document.getElementById('sb_form_q').value = 'webdriver'; console.log('webdriver')";
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript(script, element);
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService(IE_DRIVER_PATH);
Console.WriteLine(driverdetails.Port);
// open multiple IE windows using webdriver.
string url = "https://www.google.com/";
string javaScript = "window.open('" + url + "','_blank');";
IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)driver;
jsExecutor.ExecuteScript(javaScript);
Thread.Sleep(5000);
//get all opened windows (by using IE Webdriver )
var windowlist = driver.WindowHandles;
Console.WriteLine(windowlist.Count);
//loop through the list and switchto the window, and then check the url
if(windowlist.Count > 1)
{
foreach (var item in windowlist)
{
driver.SwitchTo().Window(item);
Console.WriteLine(driver.Url);
if(driver.Url.Contains("https://www.bing.com"))
{
driver.Close(); //use the Close method to close the window. The Quit method will close the browser window and dispose the webdriver.
}
}
}
Console.ReadKey();
}
Console.ReadKey();
}
I'm trying to launch a specific URL using Firefox. But I'm only able to open Firefox browser and not able to launch that URL.
class BrowserHelper
{
IWebDriver driver;
string path = Path.Combine(Environment.CurrentDirectory, #"gecko\\");
public void Navigate(string url)
{
path = path.Replace(#"\", #"\\");
var driverService = FirefoxDriverService.CreateDefaultService(path);
driverService.HideCommandPromptWindow = true;
if (driver == null)
{
driver = new FirefoxDriver(driverService);
}
driver.Url = url;
driver.Navigate().GoToUrl(driver.Url);
driver.Manage().Window.Maximize();
}
}
class Realtest
{
BrowserHelper BH = new BrowserHelper();
public void test()
{
string search ="apple";
BH.Navigate("https://www.google.com/search?q=" + search);
}
}
And I can only get this page:
Here's the final URL I want to launch: https://www.google.com.sg/search?q=apple
Any suggestions? Thanks in advance.
I have tried the below code (in Java), and it's working fine by launching the browser and loading the URL also.
System.setProperty("webdriver.gecko.driver","Drivers/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com.sg/search?q=apple");
So I feel the problem is with geckodriver version and FireFox browser installed in your local machine. I would suggest you update FireFox and geckodriver to the latest version.
There is also a pretty easy solution using the command line with c#.
Simply execute the following command to open a new Firefox Tab with the given URL:
start firefox wikipedia.de
You can also start a new Firefox instance if you wish:
start firefox -new-instance wikipedia.de
Last but not least the .Net Code to execute the commands in CLI:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
Arguments = "/c start firefox wikipedia.de",
CreateNoWindow = true,
FileName = "CMD.exe"
});
There is also a lot of other stuff that can be done with Firefox commandLine paramters. You an find all of them here:
https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options?redirectlocale=en-US&redirectslug=Command_Line_Options
This also works with chrome and opera, simply call
start opera wikipedia.de
instead of firefox.
You do not need to set driver.Url, remove that line.
driver.Navigate().GoToUrl(url);
driver.Manage().Window.Maximize();
Also, if you simply want to launch a single URL without interacting with the page, then Selenium is overkill.
I'm running a Selenium test in C# to open a URL, log in using a supplied username & password, then navigate to a page containing downloadable reports. See my code below (note: website names and usernames/passwords are withheld):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;
namespace SeleniumProject
{
class SeleniumTest
{
public static void Main(string[] args)
{
#region Constants
//User Account Information
const string username = "MyUsername";
const string password = "MyPassword";
//Initial Login Page URL and Elements
const string urlLogin = "MyURL";
const string usernameLoginName = "username";
const string passwordLoginName = "password";
const string submitLoginClassName = "btnAlign";
//Welcome Page Element
const string profileWelcomeClassName = "mstrLargeIconViewItemLink";
#endregion
int elementListIndex = 0;
IWebDriver driver = new InternetExplorerDriver();
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl(urlLogin);
driver.FindElement(By.Name(usernameLoginName)).SendKeys(username);
driver.FindElement(By.Name(passwordLoginName)).SendKeys(password);
driver.FindElement(By.ClassName(submitLoginClassName)).Click();
if (driver.Title == "Servicer Performance Profile Home. MicroStrategy")
{
try
{
driver.FindElement(By.ClassName(profileWelcomeClassName)).Click();
}
catch (NoSuchElementException ex)
{
//failed
}
}
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.XPath("//img[contains(#src,'images/freddiemac/sppdash/navigation-drawer-1.png')]")));
IReadOnlyList<IWebElement> elementList = driver.FindElements(By.XPath("//img[contains(#src,'images/freddiemac/sppdash/navigation-drawer-1.png')]"));
string mainHandle = driver.CurrentWindowHandle;
foreach (var element in elementList)
{
if (element.Displayed && elementListIndex == 5)
{
element.Click();
driver.FindElement(By.XPath("//div[contains(.,'EDR Overview')]")).Click();
break;
}
else
{
elementListIndex++;
}
}
}
}
}
What's happening is whenever I execute that last Click() event that's within the if statement nested inside of the foreach loop, instead of the normal behavior of the link opening a new tab in the same IE, it's opening as a new window and reverting back to a prior page. Normally, whenever I log into this website manually and click this link, a new tab is opened that contains another download link inside of it; that's the page I'm trying to get to.
I have no idea why this new browser window is opening with a prior page instead of even the target page I'm requesting. Could this have something to do with Selenium & IE11 not getting along? Another idea is the current login session expiring somehow, but this is all being executed in less than 10 seconds, so I wouldn't assume this is the issue.
Does anyone have any ideas?
This issue has been resolved. After many, many failed attempts at changing IE settings for handling new tabs, executing JavaScript onclick() events programmatically (instead of using native browser click commands), opening and switching between empty tabs, trying right-click keyboard commands, etc., the issue came down to IE simply not being compatible with what I was trying to do. First attempt with Google Chrome proved to be successful. The website behaved normally and links that were supposed to trigger a new tab indeed triggered the new tab.
My advice to those of you new to Selenium webdriver testing, whether your language is C# or something else, is to avoid Internet Explorer at all costs. Even with IE 11, none of what I was wanting to do worked. Test using Chrome as your first choice. Maybe it will save you three working days of troubleshooting and debugging.
I've looked extensively through Google and Stackoverflow, but i cant find a good way to implement keeping the browser open after a run and reuse it for the next run. I have it login, get text, but it closes after. I want to keep it open so I dont have relaunch the browser, login again and take more time than necessary. Simply want to use that same webpage, refresh/update the page, and get the new text(its dhtml). I have it to run every 10 seconds or so. Here what i have so far.
using (var driver = new ChromeDriver(""))
{
driver.Navigate().GoToUrl(#"");
// Get User Name field, Password field and Login Button
var userNameField = driver.FindElementByName("j_username");
var userPasswordField = driver.FindElementByName("j_password");
var loginButton = driver.FindElementByName("Submit");
// Type user name and password
userNameField.SendKeys("");
userPasswordField.SendKeys("");
// and click the login button
loginButton.Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.ClassName(""));
});
// Extract resulting message and save it into result.txt
string result = driver.FindElement(By.ClassName("")).Text;
}