Selenium clicking wrong element - c#

I have a number of tests. Sometimes if an element can't be found it just clicks on the top left of the screen. This doesn't happen all the time however it does happen. I'm not sure why this is happening. In my setUp method I'm telling it to click the element "Maximize" however if it can't find that element I put it into a catch and ignore it. For some reason when it can't find the element it just clicks on the top left corner of the screen that has the application session.
Has anyone any ideas why this is happening or is it just how selenium sometimes responds
My code is as follows
private string wordId = OfficeVersion.Word();
private string excelId = OfficeVersion.Excel();
private string powerPointId = OfficeVersion.PowerPoint();
private const string AppDriverUrl = "http://127.0.0.1:4723";
public static WindowsDriver<WindowsElement> excelSession;
public static WebDriverWait webDriverWait;
xl.Workbook WB;
public static bool skipTearDown = false;
WindowsElement create;
WindowsElement blankWorkBook;
public static DesiredCapabilities appCapabilities = new DesiredCapabilities();
[TestInitialize]
appCapabilities.SetCapability("app", excelId);
var initialSession = new WindowsDriver<WindowsElement>(new Uri(AppDriverUrl), appCapabilities);
var capabilities = new DesiredCapabilities();
capabilities.SetCapability("app", "Root");
excelSession = new WindowsDriver<WindowsElement>(new Uri(AppDriverUrl), capabilities);
webDriverWait = new WebDriverWait(excelSession, TimeSpan.FromSeconds(10));
CommonMethods.keyCheck(excelSession);
webDriverWait = new WebDriverWait(excelSession, TimeSpan.FromSeconds(10));
CommonMethods.IsElementDisplayed(excelSession, new StackTrace(true).GetFrame(0).GetFileLineNumber(), new StackTrace(true).GetFrame(0).GetMethod(), "CreateErrorIcon", "Create error when launching Excel");
try
{
This is the element I'm having trouble ignoring if it doesn't exist
webDriverWait.Until(ExpectedConditions.ElementTo‌​BeClickable(excelSession.FindElementByName("Maximize"))).Click();
}
catch (Exception)
{
//ignore
}

You can try to get the current window handle first and then attempt to locate and get the Webelement that points to the Maximize button for the window. Possibly, you might also need give a simple wait on the WebElement locate just to be safe.
This api might be useful for a C# client to selenium - driver.SwitchTo().Window(handle)
And for details, you can check here

I was running into the same problem when trying to select an item from a combo-box. Trying click on the item would always just result in a click on the top left of the screen. Super frustrating.
I got around it by using an Action to move the mouse to the element and then performing a click.
var a = new Actions(Session);
a.MoveToElement(v);
a.Click();
a.Perform();

Related

Selenium test can't click on mat-select element

Angular Material Select (mat-select) inside Form Field (mat-form-field) ignores Selenium click
When test runs, dropdown doesn't appear after click is made by Selenium. If it is made manually by me, test continues and passes.
I also tried to use SelectElement class but it's not applicable since mat-select doesn't use any select elements
public class Page definition:
[FindsBy(How = How.XPath, Using = "//*[#id='form']//mat-form-field//*[#class='mat-form-field-flex' and .//*[#formcontrolname='network']]")] // also tried all surrounding elements from DOM including mat-form-field and mat-select (look at attached screenshot)
public IWebElement _formNetworkFormControl;
public bool IsFormNetworkFormControlComponentPresent()
{
return ExtendedWebElementOperations.IsElementDisplayed(_formNetworkFormControl);
}
// Click dropdown
public void ClickFormNetworkFormControl(IWebDriver webdriver)
{
// Wait is needed until data is loaded and select is enabled
WebDriverWait wait = new WebDriverWait(webdriver, timeout: TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions.ElementToBeClickable(_formNetworkFormControl));
_formNetworkFormControl.Click();
}
// To select option after dropdown click
public void SelectByOptionName(IWebDriver webdriver, string optionName)
{
string xpath = $"//mat-option[span[text()[contains(.,'{optionName}')]]]";
WebDriverWait wait = new WebDriverWait(webdriver, timeout: TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(xpath)));
IWebElement optionNameSelect = webdriver.FindElement(By.XPath(xpath));
optionNameSelect.Click();
}
Test:
var testedPage = new Page(Driver);
testedPage.ClickAddRingTestFormNetworkFormControl(Driver); // click is made but dropdown doesn't appear
testedPage.SelectByOptionName(Driver, networkName); // if select is clicked manually, this works great
The problem is that mat-select has aria-disabled='true' until required data is loaded, so
wait.Until(ExpectedConditions.ElementToBeClickable(_formNetworkFormControl));
doesn't cover this case.
I fixed it with updating Page class following way:
public IWebElement IsElementHasTrueAriaDisabledAttribute(IWebDriver webdriver, IWebElement element)
{
if (element.GetAttribute("aria-disabled").Equals("false"))
{
return element;
}
return null;
}
public void ClickFormNetworkFormControl(IWebDriver webdriver)
{
WebDriverWait wait = new WebDriverWait(webdriver, timeout: TimeSpan.FromSeconds(15));
wait.Until<IWebElement>((d) =>
{
return IsElementHasTrueAriaDisabledAttribute(d, _formNetworkFormControl);
});
_formNetworkFormControl.Click();
}

Selenium ChromeDriver - element never got visible

I try to send keys to input field but can't do it...
I have tried different ways to wait till element is visible but got timeout exceptions...
IWebElement userName = driver.FindElement(By.Id("UserName"));
IWebElement userPassword = driver.FindElement(By.Id("Password"));
IWebElement subButton = driver.FindElement(By.XPath(("//button[contains(.,'Вхід')]")));
while (true)
{
userName = driver.FindElement(By.Id("UserName"));
if (userName.Displayed)
{
userName.SendKeys("test");
break;
}
}
subButton.Click();
Using this method gives me always timeout:
public static void WaitForElementLoad(By by, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(timeoutInSeconds));
wait.Until(ExpectedConditions.ElementIsVisible(by));
}
}
If its hidden just send/execute a simple js by selenium that will show the element. But it cant be a little bit more tricki. Set the window size to a bigger one eg 2000x2000. If something is not placed in the viewport selenium will not see it.
please try to use JavaScript to scroll to the element and then perform other operations on the element
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

How to handle JavaScript popus with controls using Selenium webdriver C# [duplicate]

So I'm working with selenium firefox webdrivers in c# winform and I have this code below to get the handle of the popup that shows when you click on the "webtraffic_popup_start_button" and it should get the handle of the popup but the popup handle is same as current one.
string current = driver.CurrentWindowHandle;
driver.FindElement(By.XPath("//*[#id='webtraffic_popup_start_button']")).Click();
Thread.Sleep(Sleep_Seconds);
popup = driver.CurrentWindowHandle;
Thread.Sleep(3000);
driver.SwitchTo().Window(current);
Thread.Sleep(1000);
Any help with this would be much appreciated thank you
This is what pop up looks like.
WebDriver does absolutely no tracking whatsoever to detect which window is actually in the foreground in the OS, and does no automatic switching when new browser windows are opened. That means the proper way to get the handle of a newly-opened popup window is a multi-step process. To do so, you would:
Save the currently-focused window handle into a variable so that you
can switch back to it later.
Get the list of currently opened window handles.
Perform the action that would cause the new window to appear.
Wait for the number of window handles to increase by 1.
Get the new list of window handles.
Find the new handle in the list of handles.
Switch to that new window.
In code using the .NET language bindings, that would look something like this:
string currentHandle = driver.CurrentWindowHandle;
ReadOnlyCollection<string> originalHandles = driver.WindowHandles;
// Cause the popup to appear
driver.FindElement(By.XPath("//*[#id='webtraffic_popup_start_button']")).Click();
// WebDriverWait.Until<T> waits until the delegate returns
// a non-null value for object types. We can leverage this
// behavior to return the popup window handle.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
string popupWindowHandle = wait.Until<string>((d) =>
{
string foundHandle = null;
// Subtract out the list of known handles. In the case of a single
// popup, the newHandles list will only have one value.
List<string> newHandles = driver.WindowHandles.Except(originalHandles).ToList();
if (newHandles.Count > 0)
{
foundHandle = newHandles[0];
}
return foundHandle;
});
driver.SwitchTo().Window(popupWindowHandle);
// Do whatever you need to on the popup browser, then...
driver.Close();
driver.SwitchTo().Window(currentHandle);
Alternatively, if you're using the .NET bindings, there's a PopupWindowFinder class in the WebDriver.Support assembly that is specifically designed to do these operations for you. Using that class is much simpler.
// Get the current window handle so you can switch back later.
string currentHandle = driver.CurrentWindowHandle;
// Find the element that triggers the popup when clicked on.
IWebElement element = driver.FindElement(By.XPath("//*[#id='webtraffic_popup_start_button']"));
// The Click method of the PopupWindowFinder class will click
// the desired element, wait for the popup to appear, and return
// the window handle to the popped-up browser window. Note that
// you still need to switch to the window to manipulate the page
// displayed by the popup window.
PopupWindowFinder finder = new PopupWindowFinder(driver);
string popupWindowHandle = finder.Click(element);
driver.SwitchTo().Window(popupWindowHandle);
// Do whatever you need to on the popup browser, then...
driver.Close();
// Switch back to parent window
driver.SwitchTo().Window(currentHandle);
If the lastly opened window is your target then simply do the following after the click
driver.SwitchTo().Window(driver.WindowHandles.ToList().Last());
EDIT
//You may need to go back to parent window to perform additional actions;
// to the new window
driver.SwitchTo().Window(driver.WindowHandles.ToList().Last());
// to the new window
driver.SwitchTo().Window(driver.WindowHandles.ToList().First());
//or
driver.SwitchTo().DefaultContent();
I've got some code you might like. The quickest solution is to use Popup Finder, but I've made my own method as well. I would never rely on the order the Window Handles are in to select the appropriate window. Popup Window Finder:
PopupWindowFinder finder = new PopupWindowFinder(driver);
driver.SwitchTo().Window(newWin);
My Custom method. Basically you pass it the element you want to click, your webdriver, and optionally the time to wait before searching after you click the element.
It takes all of your current handles and makes a list. It uses that list to eliminate the previously existing windows from accidentally getting switched to. Then it clicks the element that launches the new window. There should always be some sort of a delay after the click, as nothing happens instantly. And then it makes a new list and compares that against the old one until it finds a new window or the loop expires. If it fails to find a new window it returns null, so if you have an iffy webelement that doesn't always work, you can do a null check to see if the switch worked.
public static string ClickAndSwitchWindow(IWebElement elementToBeClicked,
IWebDriver driver, int timer = 2000)
{
System.Collections.Generic.List<string> previousHandles = new
System.Collections.Generic.List<string>();
System.Collections.Generic.List<string> currentHandles = new
System.Collections.Generic.List<string>();
previousHandles.AddRange(driver.WindowHandles);
elementToBeClicked.Click();
Thread.Sleep(timer);
for (int i = 0; i < 20; i++)
{
currentHandles.Clear();
currentHandles.AddRange(driver.WindowHandles);
foreach (string s in previousHandles)
{
currentHandles.RemoveAll(p => p == s);
}
if (currentHandles.Count == 1)
{
driver.SwitchTo().Window(currentHandles[0]);
Thread.Sleep(100);
return currentHandles[0];
}
else
{
Thread.Sleep(500);
}
}
return null;
}

Selenium Wait until element is visible issue

Got problem with proper method for waiting until element is visible.
Let me describe how page works. Page is loaded, dropdown is shown, but then, there is progress bar appearing (jquery block UI), because data is loaded from db, according to some conditions.
So i used two methods, one for wait for element to be present, then wait to dissapear, but on some occassions (maybe there are loaded in other way, etc.) i got Internet Explorer crash (so no exception by selenium, but crash of IE). Below methods and execution:
public IWebElement WaitForPageElementToLoad(By by, IWebDriver driver, int timeInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeInSeconds));
wait.Until(ExpectedConditions.ElementIsVisible(by));
return driver.FindElement(by);
}
public void WaitForPageElementToBeRemoved(By by, IWebDriver driver, int timeInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeInSeconds));
wait.Until<bool>((d) =>
{
try
{
IWebElement element = d.FindElement(by);
return false;
}
catch (NoSuchElementException)
{
return true;
}
});
}
Execution:
WaitForPageElementToLoad(By.XPath("//div[#class='blockUI blockOverlay']"), ieDriver, 25);
WaitForPageElementToBeRemoved(By.XPath("//div[#class='blockUI blockOverlay']"), ieDriver, 25);
WaitForPageElementToLoad(By.Id("clientSelector"), ieDriver, 25);
I think webdriver is searching through elements during some work, i do not how to figure that out, to write it properly. Maybe you'll have some hints, etc.

WebDriver in C# (work with windows and synchronization)

I work with webDriver in #IE9 and I find one problem. If I started tests in Run mode, then all test fail because webDriver not exists (two window ie), but if I put breakpoint in tests and start tests Debug mode I have passed all tests. Please tell me, what do, because I don't know.
This my code:
private void MyMethods(IWebdriver driver)
{
foreach (var item in driver.WindowHandles) // if I put breakpoint, I see 2 count Window Handles else this methods don't work.
{
if (driver.SwitchTo().Window(item).Title == "PortalSubMenuPopupForm")
{
driver.SwitchTo().Window(item);
break;
}
}
}
Selenium has an "issue" with IE where new windows might not appear on the WindowHandles list right away.
The solution is either
wait a fixed amount of time before calling driver.WindowHandles
or
use the WebDriverWait class to wait for the number of elements under WindowHandles to change
I think the second one is more robust. Here is a quick implementation:
public void LaunchNewWindow(IWebElement element)
{
int windowsBefore = driver.WindowHandles.Count;
element.Click();
TimeSpan timeout = new TimeSpan(0, 0, 10);
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.Until((_driver) =>
{
return _driver.WindowHandles.Count != windowsBefore;
//optionally use _driver.WindowHandles.Count > windowsBefore
});
}
Now you can use the function like so:
IWebElement clickMe = //some element that launches a new window
LaunchNewWindow(clickMe);
foreach (var item in driver.WindowHandles)
{
//etc.
}

Categories

Resources