Click fails because the element is not visible - c#

I'm using the following to click an element on a web page:
driver.FindElement(By.Name("SearchIcon")).Click();
HTML:
<span class="ticon ti-search ti-1x" name="SearchIcon"> </span>
It's suppose to be very easy and strait forward but I'm getting:
"{"errorMessage":"Element is not currently visible and may not be manipulated","request":{"headers":{"Accept":"application/json, image/png","Connection":"Close","Content-Length":"0","Content-Type":"application/json;charset=utf-8","Host":"localhost:54912"},"httpVersion":"1.1","method":"POST","post":"","url":"/click","urlParsed":
Putting a
NUnit.Framework.Assert.IsTrue(driver.FindElement(By.Name("SearchIcon")).Enabled);
before the click statement passes so apparently the element is there and visible once the test runs so I don't get what's wrong here.

I know this is a bit old but I stumbled across it. It may help others.
You could create an extension method that checks if an element exists:
public static bool Exists(this IWebElement element)
{
try
{
var text = element.Text;
}
catch (NoSuchElementException)
{
return false;
}
return true;
}
You could then Assert like:
var searchIcon = driver.FindElement(By.Name("SearchIcon"));
NUnit.Framework.Assert.IsTrue(searchIcon.Exists());

Related

how to Check invisibility of Element X, if it is invisible, click this Element Y

I want to check if "X" element is visible, if it is not visible, then click button "Y" that will display button "X"
I tried the following examples
This first example, breaks due to "driver" is unable to find this locator. What is the best approach to check if this element is Not visible and then click the other button in order to display it?
if (!(driver.findelement(XBUTTONlocator).Displayed))
{
driver.Navigate().GoToUrl(VariablesConstants.ManageWizardURL);
Thread.Sleep(2000);
YBUTTONlocator.Click();
Assert.IsTrue(driver.FindElement(By.CssSelector("")).Displayed);
}
I also have this Expected condition but I do not know of how to implement it in a IF, and then make an action.
public static Func<IWebDriver, bool> InvisibilityOfElementLocated(By locator)
{
return (driver) =>
{
try
{
var element = driver.FindElement(locator);
return !element.Displayed;
}
catch (NoSuchElementException)
{
return true;
}
catch (StaleElementReferenceException)
{
return true;
}
};
HTML of button I want to verify it's displayed:
<span translate="" class="ng-scope ng-binding">Create Distribution Group</span>
driver.FindElement will return the located WebElement if found or will throw NoSuchElementException if not. You can use driver.FindElements. If the returned list is empty the element doesn't exist, and if the list is not empty you can use index to check visibility of the element
ReadOnlyCollection<IWebElement> elements = driver.FindElements(XBUTTONlocator);
if (elements.Count == 0 || !elements[0].Displayed)
{
}
Try/catch should work.
try{
driver.findelement(XBUTTONlocator).click()
}
catch (NoSuchElementException) {
YBUTTONlocator.click()
}
Conversely you could also use findElements and check to see if it's size is 0.
if(driver.findelements(XBUTTONlocator).size > 0) {
driver.findelements(XBUTTONlocator).click()
} else {
YBUTTTONlocator.click()
}

Selenium MoveToElement not working if element not found by XPath

Having issues with the MoveToElement function in Selenium Webdriver for C#. The MoveToElement doesn't seem to do anything.
I have the following HTML:
<div id="rounded-navigation-with-icons">
<ul>
<li class="navigation-item">
<ul>
<li>
</li>
</ul>
</li>
</ul>
</div>
The inner-most list is hidden initially, until the navigation-item is hovered over by the mouse.
I then have the following code to click the navigation-item-title, which is visible to Selenium, and then click the MembersTestPage link.
public bool SearchForElement(string elementToFind, Page.FindBy by)
{
var navigation = Page.FindElement("rounded-navigation-with-icons", Page.FindBy.ID);
if (navigation != null)
{
foreach (var item in navigation.FindElements(By.ClassName("navigation-item")))
{
var titleElements = Page.FindElements("navigation-item-title", Page.FindBy.ClassName);
Actions action = new Actions(Driver.Instance);
foreach (var moveToItem in titleElements)
{
try
{
// Move to the main navigation link container element, but it doesn't work
action.MoveToElement(moveToItem);
// Move the mouse position manually to the link's location
action.MoveByOffset(moveToItem.Location.X, moveToItem.Location.Y);
// This does correctly find the element
var element = Page.FindElement("a[href='MembersTestPage']", Page.FindBy.CssSelector);
action.MoveToElement(element);
// Click returns that the element is hidden/invisible and therefore cannot be clicked
element.Click();
return true;
}
catch (Exception)
{
}
}
}
}
return false;
}
You can see I have used MoveToElement by passing the element, and also by manually passing the X and Y values of the item, but neither are working.
If I find the elements by XPath, this works as expected.
What am I doing wrong? Thanks
When using Actions in Selenium, then you have to finally call the Perform() method, bc otherwise the actions are only collected internally but never executed in the browser.
You can either call
action.Perform();
or
action.Build().Perform();
It doesn't matter. If you omit the Build(), then Perform() implicitly calls it.
I had similar problem recently and my solution was to perform everything as one action:
action.MoveToElement(moveToItem)
.MoveByOffset(moveToItem.Location.X, moveToItem.Location.Y)
.MoveToElement(Page.FindElement("a[href='MembersTestPage']", Page.FindBy.CssSelector))
.click(Page.FindElement("a[href='MembersTestPage']", Page.FindBy.CssSelector))
.build()
.perform();

selenium unable to find element button

i am trying to get this button with selenium in c#
<a id="1|0AqnCSdkjQ0|none" href="" target="_self" rel="nofollow" class="download_link 1">Download</a>
i tried with id and class but it didn't work.
Here is the web page:
http://www.mp3juices.cc/ - > on the next page
Your code is failing with that "Compound class" error because you are, basically, asking for two class names.
The button has the class download_link.
If you do something like driver.findElements(By.className("download_link")) you'll get a List of all the buttons, and get whichever you wanted.
(The above snippet is Java, so you may have to adapt it to C#)
you can use this as a solution
driver.findElement(By.xpath("//a[#class='download_link 1'] and contains(text(),'Download')"));
Did you try
driver.FindElement(By.CssSelector("a.download_link.2")
When you tried to use "download_link 2" you were requesting two class names. You can specify two class names (or more) in a CSS Selector and put a period between them. The CSS selector above is read as find an A tag with class download_link and class 2.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
try
{
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
try
{
return d.FindElement(By.ClassName("dl_link 1"));
}
catch
{
return null;
}
});
}
catch(Exception e)
{
}
ReadOnlyCollection<IWebElement> lists = driver.FindElements(By.ClassName("download_link"));
lists[0].Click();
*The code is not optimized, but it works great. (First part i am using to wait for the button to be loaded).

Selenium webdriver: IE 11 element.Click() doesnt work

I tried to find any solution but nothing is not helped me.
I have this element
<span data-lkd="GUI-411396" data-lkta="tc" data-lkda="title" class="panelbar_item" title="Hledat">Form</span>
In Selenium I find it with
IWebElement form = GetElementAndWaitForEnabled(By.CssSelector("span[data-lkd=\'GUI-411396\']"));
It's not problem to this part. But if try click on this element in IE11 nothing happend
find.Click()
I tried some solution like:
driver.SwitchTo().Window(driver.CurrentWindowHandle);
find.SendKeys(Keys.Enter);
find.Click();
But nothing happend. In Chrome and Firefox is normaly click on element.
If I clik in other elements for example button it works on IE 11. But I need click on this element.
I'm using Selenium v2.46.0, IE 11 (x86, x64).
With IE, it's always something extra you should do. Try this "special" trick:
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].click();", find)
It looks like you are trying to click on a span element. Instead of using a work around to click on the span element and trying to get the desired effect, try checking to see if it is wrapped in an anchor element or input / button element.
As an aside a good practice is to remember to always scroll the element into view, an example wrapper function would be:
public static void clickElementAsUser(WebDriver driver, By by)
{
WebElement element;
try
{
element = driver.findElement(by);
scrollElementIntoView(driver, element);
Thread.sleep(100); //Wait a moment for the element to be scrolled into view
element.click();
}
catch(Exception e) //Could be broken into multicatch
{
//Do Something
}
}
public static void scrollElementIntoView(WebDriver driver, WebElement element)
{
try
{
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);
}
catch(Exception e)
{
//Do Something
}
}
If you post a small code sample of what is aroudn the span I may be able to help further. Goodluck!

How to scroll to element with Selenium WebDriver

How do I get Selenium WebDriver to scroll to a particular element to get it on the screen. I have tried a lot of different options but have had no luck.
Does this not work in the C# bindings?
I can make it jump to a particular location ex
((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight - 150)");
But I want to be able to send it to different elements without giving the exact location each time.
public IWebElement Example { get { return Driver.FindElement(By.Id("123456")); } }
Ex 1)
((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", Example);
Ex 2)
((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollBy(Example.Location.X", "Example.Location.Y - 100)");
When I watch it, it does not jump down the page to the element, and the exception matches the element being off screen.
I added an bool ex = Example.Exists(); after it and checked the results.
It does Exist (its true).
Its not Displayed (as its still offscreen as it has not moved to the element)
Its not Selected ??????
Someone is seeing success By.ClassName.
Does anyone know if there is a problem with doing this By.Id in the C# bindings?
Its little older question, but I believe that there is better solution than suggested above.
Here is original answer: https://stackoverflow.com/a/26461431/1221512
You should use Actions class to perform scrolling to element.
var element = driver.FindElement(By.id("element-id"));
Actions actions = new Actions(driver);
actions.MoveToElement(element);
actions.Perform();
This works for me in Chrome, IE8 & IE11:
public void ScrollTo(int xPosition = 0, int yPosition = 0)
{
var js = String.Format("window.scrollTo({0}, {1})", xPosition, yPosition);
JavaScriptExecutor.ExecuteScript(js);
}
public IWebElement ScrollToView(By selector)
{
var element = WebDriver.FindElement(selector);
ScrollToView(element);
return element;
}
public void ScrollToView(IWebElement element)
{
if (element.Location.Y > 200)
{
ScrollTo(0, element.Location.Y - 100); // Make sure element is in the view but below the top navigation pane
}
}
This works for me:
var elem = driver.FindElement(By.ClassName("something"));
driver.ExecuteScript("arguments[0].scrollIntoView(true);", elem);
This works for me in C# automation:
public Page scrollUp()
{
IWebElement s = driver.FindElement(By.Id("your_locator")); ;
IJavaScriptExecutor je = (IJavaScriptExecutor)driver;
je.ExecuteScript("arguments[0].scrollIntoView(false);", s);
return this;
}
I created a extension for IWebDriver:
public static IWebElement GetElementAndScrollTo(this IWebDriver driver, By by)
{
var js = (IJavaScriptExecutor)driver;
try
{
var element = driver.FindElement(by);
if (element.Location.Y > 200)
{
js.ExecuteScript($"window.scrollTo({0}, {element.Location.Y - 200 })");
}
return element;
}
catch (Exception ex)
{
return null;
}
}
For scroll down inside the page here I have small code and solution
My Scenario was until I scroll down the page. Accept and Don't accept button was not getting enabled. I was having 15 terms and conditions from which I needed to select 15th term and condition by inspecting webpage and taking the Id of last terms and condition paragraph.
driver.FindElement(By.Id("para15")).Click();
<div id="para15">One way Non-Disclosure Agreement</div>
I had somehow same problem. I was working on a web page and need to click on a button on a child window which by default, was located below screen.
This is the code I used and it worked.
Actually I just simulated a mouse drag and drop and moved the window 250 points upwards so that the button was in the screen.
Actions action = new Actions(driver);
action.DragAndDropToOffset(driver.FindElement(By.XPath("put an element path which **is in the screen now**, such as a label")), 0, -250);
action.Build().Perform();
If the reason we put time is for a long time to load the page, we put it. Just it.
ChromeOptions options = new ChromeOptions();
var driver = new ChromeDriver(options);
driver.Navigate().GoToUrl("https://www.w3schools.com/");
Thread.Sleep(5000);
driver.ExecuteScript("scroll(0,400)");
HtmlDocument countriesDocument = new HtmlDocument();
countriesDocument.LoadHtml(driver.PageSource);
I am providing solution to scroll within a specific element, like a scrollable table.
// Driver is the Selenium IWebDriver
IJavaScriptExecutor exec = (IJavaScriptExecutor) Driver;
int horizontalScroll= direction == Direction.Right ? X : 0;
int verticalScroll = direction == Direction.Down ? Y : 0;
exec.ExecuteScript(
"arguments[0].scrollBy(arguments[1], arguments[2])"
, Self
, horizontalScroll
, verticalScroll);
Actions actions = new Actions(driver);
actions.SendKeys(Keys.PageDown).Build().Perform();
You do it through for, it works like clockwork, simple, but not always convenient
var js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'})", PutYourElementIDHere);
var e = driver.FindElement(By.XPath("//*[text()='Timesheet']"));
// JavaScript Executor to scroll to element
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", e);

Categories

Resources