c# selenium How to click on a checkbox - c#

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 .

Related

Using Selenium, Find List Item and Click On It

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();

How to click button using selenium c#

<button class="btn btn-outline-primary btn-lg" id="btnPermission">GO</button>
The above codes are from a website, however I am unable to click this button despite trying multiple attempts. What should I do?
IWebElement reklamgec3 = driver.FindElement(By.CssSelector("#btnPermission"));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", reklamgec3);
IWebElement reklamgec3 = driver.FindElement(By.ClassName("btn-outline-primary"));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", reklamgec3)
IWebElement reklamgec3 = driver.FindElement(By.XPath("//*[#id="btnPermission"]"));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", reklamgec3)
IWebElement reklamgec3 = driver.FindElement(By.Id("btnPermission"));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", reklamgec3)
IWebElement reklamgec3 = driver.FindElement(By.CssSelector("#btnPermission"));
reklamgec3.Click();
How to click button using c# selenium. The above does not work for me.
You need to use an explicit wait:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(d => d.FindElement(By.Id("btnPermission")).Click());
Waiting for the existence of a element is frequently not enough. You need to wait for it to be clickable. Many times that just means attempting to find then click the element until the click event succeeds.

C# Selenium not consistent on different machines [duplicate]

I'm using Selenium.WebDriver for C# to ask a question on Quora just typing my question in notepad.
Everything worked fine since I had to post it.
To post it I need to click on a link inside a span like this:
<span id="__w2_wEA6apRq1_submit_question">
<a class="submit_button modal_action" href="#" id="__w2_wEA6apRq1_submit">Add Question</a>
</span>
In order to click it I've tried this method, that I've used for all my previous button clicks:
Selecting the element and clicking it:
var element = driver.FindElement(By.CssSelector(".submit_button.modal_action"));
element.Click();
Doing so I can get the element, but unfortunately it throws "ElementNotVisibleException". Debugging my application I could see that Displayed property was set to False, while it wasn't, because in my ChromeDriver I could clearly see the button.
To avoid clicking the element, I tried IJavaScriptExecutor and Driver.ExecuteJavaScript(); to click the link through a script:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].click()", element);
Same logic has been used for Driver.ExecuteJavaScript(); but I get the same result, but when I write the same script into DevTools's Console tab it works perfectly.
How can I solve this issue?
You might have a case where the button become displayed(visible) after your check is executed, so you might try following delay in order to ensure that the button is displayed at the time of check:
public static void WaitForElementToBecomeVisibleWithinTimeout(IWebDriver driver,
IWebElement element, int timeout)
{
new WebDriverWait(driver,
TimeSpan.FromSeconds(timeout)).Until(ElementIsVisible(element));
}
private static Func<IWebDriver, bool> ElementIsVisible(IWebElement element)
{
return driver =>
{
try
{
return element.Displayed;
}
catch (Exception)
{
// If element is null, stale or if it cannot be located
return false;
}
};
}
If the button is not visible in the viewport(i.e. need scrolling to become visible) then you may scroll it with
public static void ScrollElementToBecomeVisible(IWebDriver driver, IWebElement element)
{
IJavaScriptExecutor jsExec = (IJavaScriptExecutor)driver;
jsExec.ExecuteScript("arguments[0].scrollIntoView(true);", element);
}
As per the HTML you have shared to click on the element with text as Add Question as the element is within a Modal Dialog you need to induce WebDriverWait for the desired ElementToBeClickable and you can use either of the following Locator Strategies as solutions:
LinkText:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.LinkText("Add Question"))).Click();
CssSelector:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("span[id$='_submit_question']>a.submit_button.modal_action"))).Click();
XPath:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//span[contains(#id,'_submit_question')]/a[#class='submit_button modal_action' and contains(.,'Add Question')]"))).Click();

Selenium C# ElementNotVisibleException: element not interactable but the element is actually visible

I'm using Selenium.WebDriver for C# to ask a question on Quora just typing my question in notepad.
Everything worked fine since I had to post it.
To post it I need to click on a link inside a span like this:
<span id="__w2_wEA6apRq1_submit_question">
<a class="submit_button modal_action" href="#" id="__w2_wEA6apRq1_submit">Add Question</a>
</span>
In order to click it I've tried this method, that I've used for all my previous button clicks:
Selecting the element and clicking it:
var element = driver.FindElement(By.CssSelector(".submit_button.modal_action"));
element.Click();
Doing so I can get the element, but unfortunately it throws "ElementNotVisibleException". Debugging my application I could see that Displayed property was set to False, while it wasn't, because in my ChromeDriver I could clearly see the button.
To avoid clicking the element, I tried IJavaScriptExecutor and Driver.ExecuteJavaScript(); to click the link through a script:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].click()", element);
Same logic has been used for Driver.ExecuteJavaScript(); but I get the same result, but when I write the same script into DevTools's Console tab it works perfectly.
How can I solve this issue?
You might have a case where the button become displayed(visible) after your check is executed, so you might try following delay in order to ensure that the button is displayed at the time of check:
public static void WaitForElementToBecomeVisibleWithinTimeout(IWebDriver driver,
IWebElement element, int timeout)
{
new WebDriverWait(driver,
TimeSpan.FromSeconds(timeout)).Until(ElementIsVisible(element));
}
private static Func<IWebDriver, bool> ElementIsVisible(IWebElement element)
{
return driver =>
{
try
{
return element.Displayed;
}
catch (Exception)
{
// If element is null, stale or if it cannot be located
return false;
}
};
}
If the button is not visible in the viewport(i.e. need scrolling to become visible) then you may scroll it with
public static void ScrollElementToBecomeVisible(IWebDriver driver, IWebElement element)
{
IJavaScriptExecutor jsExec = (IJavaScriptExecutor)driver;
jsExec.ExecuteScript("arguments[0].scrollIntoView(true);", element);
}
As per the HTML you have shared to click on the element with text as Add Question as the element is within a Modal Dialog you need to induce WebDriverWait for the desired ElementToBeClickable and you can use either of the following Locator Strategies as solutions:
LinkText:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.LinkText("Add Question"))).Click();
CssSelector:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("span[id$='_submit_question']>a.submit_button.modal_action"))).Click();
XPath:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//span[contains(#id,'_submit_question')]/a[#class='submit_button modal_action' and contains(.,'Add Question')]"))).Click();

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();

Categories

Resources