Using Selenium, Find List Item and Click On It - c#

I'm trying to click on a unordered list element for the element id = search_explorer, but can figure out how to find the drop down list item so I can click on it. Here is the elements and what I have tried. ele returns null. Can someone please help me?
<ul class="menu menu_header dropit">
<li class="dropit-trigger menu_tools_item dropit-open"> KEYWORD
<ul style="width: 175px;" class="dropit-submenu">
<li class="menu menu_header menu_header_item dropit menu_tools_item" id="keyword_explorer" domain="0"><a class="menu_tools_item_a" href="#">Keyword Explorer</a></li>
<li class="menu menu_header menu_header_item dropit menu_tools_item" id="search_explorer" domain="0"><a class="menu_tools_item_a" href="#">Search Explorer</a></li>
</ul>
</li>
</ul>
ele = driver.FindElements(By.CssSelector(".menu.menu_header.menu_header_item.dropit.menu_tools_item")).FirstOrDefault(x => x.Text == "Search Explorer");
ele.Click();

It seems you need to click on drop down element to open the list and click on the specific element. Use WebDriverWait() and wait for ElementToBeClickable()
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector(".menu.menu_header.dropit")));
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector("#search_explorer >a")));

----Update---
Based on the updated information from the comments:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Use Actions to simulate mouse movement
Actions action = new Actions(driver);
// Move to the first element to hover
action.MoveToElement(driver.FindElement(By.CssSelector(".dropit-trigger")));
// Wait for search_explorer element to be visible
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("search_explorer")));
// Assign the search_explorer element to a variable
var searchExplorer = driver.FindElement(By.Id("search_explorer"));
// Move to the search_explorer element now that it's visible
action.MoveToElement(searchExplorer);
// call Actions.Perform() to execute the actions in the browser
action.Perform();
// Now click search_explorer element
searchExplorer.Click();

Related

Selenium Webdriver C#, Chrome, the icon hides the element and it is not clickable [duplicate]

This question already has answers here:
Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click
(9 answers)
Closed 4 years ago.
Update: The main problem was that element icon hid a button and it was not clickable. Solution was, using js.Executor, to hide this icon.
I am trying to use Selenium WebDriver for tests, it is new for me, and I have a problem with one element, it is no clickable, I tried find it by linktext, classname, cssselector, it does not work.
I have already read a lot of about this issue "Element is not clickable" , but have not found solution for my test. Hope, you will give me good advice.
Chrome version 67.0.3396.99, 64 bit
Visual C# 2017
Webdriver version 3.13.1.0
Here is my script:
namespace MK_edit
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver(#"C:\Users\alina\ProjectLibre");
driver.Url = "http://test.test.com"; //not real url, I cannot show it
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
driver.Manage().Window.Maximize();
//close popup
driver.FindElement(By.CssSelector("div.whatsnew-content"));
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
driver.FindElement(By.CssSelector("button.btn.btn-success")).Click();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
//edit part
var lab = driver.FindElement(By.CssSelector("span.glyphicon.glyphicon-edit"));
lab.Click();
}
}
}
Element info:
<li class="allwaysVisible"><span class="glyphicon glyphicon-edit"></span></li>
Error message:
Element <span class=\"glyphicon glyphicon-edit\">
</span> is not clickable at point (312, 24).
Other element would receive the click: <div class=\"modal-backdrop fade\">
</div>\n
Thank you!
As per error message you have shared, <div class=\"modal-backdrop fade\"> would recieve the click and not <span class=\"glyphicon glyphicon-edit\">. You cannot interract with your element until div element hovers your element. It means div, if it is a popup or dialogue, should be closed. Or if it is a element which automatically dissapears, you have to wait until this element will be not more visible. Then you can click on your element.
I cannot provide the code sample to solve your issue, since I don't have a link to website. Hope this helps.
Wait until the spinner/loader disappears, try passing the spinner element ".modal-backdrop" inside a method like this...
public static void WaitForNotVisible(IWebElement element, IWebDriver driver)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(drv =>
{
try
{
if (element.Displayed)
{
return false;
}
return true;
}
catch
{
return true;
}
});
}
Like this...
var spinnerElement = driver.FindElement(By.CssSelector(".modal-backdrop"));
WaitForNotVisible(spinnerElement, driver);
labosana.Click();
Please add some wait before finding the labosana element
Code:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("span.glyphicon.glyphicon-edit")));
var labosana = driver.FindElement(By.CssSelector("span.glyphicon.glyphicon-edit"));
labosana.Click();
You may replace click event with action class,
Actions builder = new Actions(driver);
builder.MoveToElement("Your target element").Click().Perform();
My element became visible and clickable after such additions, tnx for advices
//open edit
var lab = driver.FindElement(By.CssSelector("a[title=\"---\"]"));
var icon = driver.FindElement(By.CssSelector("span.glyphicon.glyphicon-edit"));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].style='display: none;'", icon);
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
wait.Until(ExpectedConditions.ElementToBeClickable(lab));
lab.Click();

c# selenium How to click on a checkbox

I would like to click a chechbox through C# and Selenium. The checkbox HTML is as follows :
<div class="ad-post-rules" ng-class="{'ad-post-rules-error': submitted && addClassifiedForm.postRulesCheck.$error.required}" an-form-error="" an-form-error-optional-text="İlan verme kurallarını onaylamadınız."><input id="postRulesCheck" class="checkBox sg-checkbox ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" type="checkbox" value="1" name="postRulesCheck" ng-model="postRulesCheck" required="" an-form-object-name="İlan Verme Kuralları"><label for="postRulesCheck"></label><span class="rulesOpen" ng-click="adPostRules=true">İlan verme kurallarını</span><label for="postRulesCheck">okudum, kabul ediyorum</label></div>
My code is as follows :
Dim cekbul As IWebElement
System.Threading.Thread.Sleep(1000)
cekbul = driver.FindElement(By.Id("#postRulesCheck"))
cekbul.Click()
I dont know coding in c sharp but i think it works
IWebElement Ele_CheckBox = driver.FindElement(By.Id("postRulesCheck"));
Ele_CheckBox.Click();
By using name
IWebElement Ele_CheckBox = driver.FindElement(By.Name("postRulesCheck"));
Ele_CheckBox.Click();
By xpath
IWebElement Ele_CheckBox = driver.FindElement(By.Xpath("//input[#id='postRulesCheck']"));
Ele_CheckBox.Click();
To click on the checkbox as the element is an Angular element you have to induce WebDriverWait for the elelemt to be clickable and you can use either of the following option :
CssSelector :
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("input.checkBox.sg-checkbox.ng-pristine.ng-untouched.ng-empty.ng-invalid.ng-invalid-required#postRulesCheck"))).Click();
XPath :
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[#class='checkBox sg-checkbox ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required' and #id='postRulesCheck']"))).Click();
Selenium can click only on element that is visible for a human. You can still execute javascript even if the element is not visible. If the element is visible for a human while you are trying to execute your test and still you are getting the element not visible exception , try to use Actions API instead otherwise use javascript.
Actions action = new Actions(driver);
IWebElement cekbul = driver.FindElement(By.Id("postRulesCheck"));
action.Click(cekbul).Build().Perform();
This lets you click at a point irrespective of the location of point .

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 unhide elements C#

I have Menu Group:
<div class="menuGroup">
Some of this div contain class which hide or show menu contents
class="toggleMenuChildren">
When you click on it, it change on
class="toggleMenuChildren opened">
So I want show all content from menu (click on all classes toggleMenuChildren) to show it.
I try this
IWebElement zi = driver.FindElement(By.ClassName("toggleMenuChildren"));
zi.Click();
But this opened (unhide) just first element, and if you call it again then hide content. How I can show all content (click on all elements) ?
You can use xpath - //div[contains(#class,'toggleMenuChildren') and not(contains(#class,'opened'))]
(sorry it is in java)
List<WebElement> allElements = driver.findElements(By.xpath("//div[contains(#class,'toggleMenuChildren') and not(contains(#class,'opened'))]"));
for(WebElement ele: allElements){
ele.click;
}
You can try to use hover to show all the information under toggleMenuChildren class
Actions actions = new Actions(driver);
IWebElement menuHoverLink =
driver.FindElement(By.XPath("//div[#class='toggleMenuChildren']"));
actions.MoveToElement(menuHoverLink);
actions.Build().Perform();
//That is the elements under the toggleMenuChildren class that you can use
driver.FindElement(By.PartialLinkText("...")).Click();
after perform() line all the elements will be unhided .

How to get lookup list item using Selenium 2.0 with C#

Im trying to select an item from lookup list, its not like drop down list. If you write something that matches the contents of the lookup list, all the matching contents show up in the list and you cannot simply type in the text field even if you know the item from lookup list, you HAVE to click on the item from lookup list in order for it to populate in the text field.
What Im doing is, Im writing the complete text of a valid field value in the field so that it is the only item that appears in the lookup list and then trying to search that list item so that it can be clicked, but whatever i try, the item isnt found. here is what I have tried already:
here is the html:
<body>
<div class="body-home"></div>
<script type="text/javascript"></script>
<script></script>
<div id="cboxOverlay" style="display: none;"></div>
<div id="colorbox" class="" style="display: none;"></div>
<ul id="ui-id-1" class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all" tabindex="0" style="z-index: 1; display: none; top: 456.783px; left: 468.033px; width: 247px;">
<li class="ui-menu-item" role="presentation">
<a id="ui-id-27" class="ui-corner-all" tabindex="-1">
<span style="padding:10px;"></span>
</a>
</li>
The last tag in above html is the one Im trying to get.
here is the xpath that i tried, ive tried the cssSelecter as well, nothing works.
IWebElement selectItem = driverX.FindElement(By.XPath("/ul[#id='ui-id-1']/li[1]/a"));
selectItem.Click();
Any help is highly appreciated.
Sophia
In order to type/select and item from lookup list, you should initially click the parent that contains the ul/li items. When you click the parent of it, the style associated with the ul/li (display: none) will be removed, so that you can interact with the ul/li.
From the HTML posted, we can observe that UL has a style with attributed display: none, this means we can't interact with it or with its children. If you post the complete HTML/the website url, may we can find the solution.
For example, check this website, which has similar kind of lookup list and below is the solution.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium;
namespace TestSelenium
{
[TestClass]
public class UnitTest1
{
public ChromeDriver browser;
[TestMethod]
public void TestMethod1()
{
try
{
browser = new ChromeDriver();
browser.Navigate().GoToUrl("https://roofandfloor.com/");
System.Threading.Thread.Sleep(5000);
// Select City.
IWebElement parentDiv = browser.FindElement(By.ClassName("city-dropdown-search"));
parentDiv.Click();
this.SelectItem("Bangalore");
// Select Property.
parentDiv = browser.FindElement(By.ClassName("property-type-checkboxes"));
parentDiv.Click();
this.SelectItem("Villa");
// Select Bed room. Need to write separate code for this.
parentDiv = browser.FindElement(By.ClassName("bedroom-select-container"));
parentDiv.Click();
System.Threading.Thread.Sleep(1500);
IWebElement items = browser.FindElement(By.ClassName("search-bedrooms"));
foreach (IWebElement item in items.FindElements(By.TagName("span")))
{
if (item.Text.Contains("1 BHK"))
{
item.Click();
break;
}
}
// Select Max budget.
parentDiv = browser.FindElement(By.Id("s2id_priceMax"));
parentDiv.Click();
this.SelectItem("5 Lakhs");
// Select Build up area.
parentDiv = browser.FindElement(By.Id("s2id_areaMin"));
parentDiv.Click();
this.SelectItem("600 Sq.ft.");
// Select Possession.
parentDiv = browser.FindElement(By.Id("s2id_possessionDate"));
parentDiv.Click();
this.SelectItem("Ready to Occupy");
}
catch
{ }
}
private void SelectItem(string itemText)
{
System.Threading.Thread.Sleep(1500);
IWebElement items = browser.FindElement(By.Id("select2-drop"));
foreach (IWebElement item in items.FindElements(By.TagName("li")))
{
if (item.Text.Contains(itemText))
{
item.Click();
break;
}
}
}
}
}
Try to observe the HTML of the posted portal. The above solution works fine to select the lookup items.
Sophia,
Maybe you should try the most literal test 1st, i.e. by a known Id to see that it works:
IWebElement selectItem = driverX.FindElement(By.Id("ui-id-27"));
selectItem.Click();
Once you've established this, then you can really look closely at the generic structure (obviously using ui-id-27 is for this test only). I would then move onto looking at the XPath structure in the real case and establish a test between the presented Id and the generic Xpath element.

Categories

Resources