How do you click on a checkbox from a list of checkboxes via Selenium/Webdriver in Java? - selenium

I'm using Selenium 2 (Webdriver) for automating tests on a webpage. However I wonder if there is way to check checkbox from the list of checkboxes using webdriver framework?
I tried this code but no avail:
IWebElement box = ffDriver.FindElement(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_Adde_div']"));
List<IWebElement> chkbox = box.FindElements(By.TagName("input"));
ffDriver.FindElement(By.Id("ctl00_ContentPlaceHolder1_Add_lstCategory_0"));
//chkbox.g(2).click();

If you already know the id of the checkbox, you can use this method to click select it:
string checkboxXPath = "//input[contains(#id, 'lstCategory_0')]"
IWebElement elementToClick = driver.FindElement(By.XPath(checkboxXPath));
elementToClick.Click();
Assuming that you have several checkboxes on the page with similar ids, you may need to change 'lstCategory_0' to something more specific.
This is written in C#, but it shouldn't be difficult to adapt to other languages. Also, if you edit your post with some more information, I can fine-tune this example better.
Let me know if this works!
I've visited the site and successfully interacted with the checkboxes in the dropdown widget using this code:
/** Set XPath Variables **/
string dropdownWidgetXPath = "//span[contains(#id, 'selInd')]";
string checkboxXPath = "//input[contains(#id, 'selInd')]";
/** Navigate to the page **/
driver.Navigate().GoToUrl("http://www.jobserve.com/us/en/Job-Search/");
/** Click the dropdown widget **/
IWebElement dropdownWidgetElement = driver.FindElement(By.XPath(dropdownWidgetXPath));
dropdownWidgetElement.Click();
/** Identify all checkboxes present **/
var allCheckboxes = driver.FindElements(By.XPath(checkboxXPath));
/** Click each checkbox and wait so that results are visible **/
foreach(IWebElement checkbox in allCheckboxes)
{
checkbox.Click();
System.Threading.Thread.Sleep(500);
}

In Selenium webdriver you can do it like this :
All the check-boxes must be having some unique identifier then you can simply find it out by Id If they dont have a unique id (This is what I encountered while testing a web application) then it must be having some title and name attribute (or some other attribute).
Then you can try this :
driver = new FirefoxDriver();
driver.findElement(By.xpath("//input[#name='mycheckboxgroup' and #title='movies']")).click();
driver.findElement(By.xpath("//input[#name='mycheckboxgroup' and #title='songs']")).click();

By id of the checkbox you could use following code:
IWebElement elementToClick = driver.FindElement(By.ID(ctl00_ContentPlaceHolder1_Add_lstCategory_0));
elementToClick.Click();
If you don't know id then use below code by xpath:
String checkbox = "//input[#type='checkbox']"
IWebElement elementToClick = driver.FindElement(By.XPath(checkbox ));
elementToClick.Click();

The code in selenium is simple:
new WebDriverWait(driver, TimeSpan.FromSeconds(timeToHoldOn)).Until(ExpectedConditions.ElementExists((By.ClassName("ckb"))));
IWebElement dropdownWidgetElement = driver.FindElement(By.ClassName("ckb"));
dropdownWidgetElement.Click();
Thread.Sleep(1000);
var allCheckboxes = driver.FindElements(By.ClassName("ckb"));
foreach (IWebElement checkbox in allCheckboxes) {
checkbox.Click();
System.Threading.Thread.Sleep(250);
}

This is how I check and uncheck all my boxes, it has to have an Id or class.
Id example:
driver.FindElement(By.Id("someid")).click();
ClassName examaple:
driver.FindElement(By.ClassName("someid")).click();
Its short, its sweet and more importantly it works.

Try using this piece of code written in java
String checkboxes = "//*[#type='checkbox']";
List<WebElement> elementToClick = driver.findElements(By.xpath(checkboxes));
for (WebElement AllCheck : elementToClick) {
AllCheck.click();
}

Java, Clicking on multiple checkboxes at a time using the loop.
**Sample Xpath :**
CheckBox1 Xpath : //input[#class='mycheck' and #id='1']
CheckBox2 Xpath : //input[#class='mycheck' and #id='2']
Get all the elements checkbox using findelements:
List WebElement ele =
driver.findElements(By.xpath("//input[#class='mycheck']"));
Make the Xpath as string by leaving the ID and assign the ID as i.
for(int i=1; i<=ele.size(); i++) { driver.findElement(By.xpath("//input[#class='mycheck' and #id='" + + i + "']")).click(); }
i gets the value for every loop and the xpath matches the checkbox and click's it.

You can select each of the radio buttons/checkboxes by selecting the element which contains them and iterating through each one just like an array.
For example, here a ul element contains some radio buttons. I select the ul element first, then I can select each radio by using the correct index (inside the [])
//Select the ul containing the radio buttons I want to click/select
var ul = driver.FindElement(By.Id("ul_containing_radio_buttons"));
//use forloop to click each button in turn
for (var i = 2; i <= 0; i--)
{
var button= ul.FindElements(By.TagName("input"))[i];
//i is the index of the radio button in out ul element
button.Click();
}

Related

How to find a webelement that has 'checked' attribute in list of child WebElements through Selenium using Katalon Studio

I have radio buttons that when either radio button is selected, it gets a checked attribute.
This is how the HTML looks:
My implementation of getting the descendant that has a checked attribute:
public TestObject getCheckedTestObjectFromParent(String parentID){
WebDriver driver = DriverFactory.getWebDriver()
WebElement parentWebElement = driver.findElement(By.id(parentID))
List<WebElement> children = parentWebElement.findElements(By.xpath(".//*"))
println(children.size())
for(int i = 0; i < children.size(); i++){
TestObject childTestObject = getTestObjectFromWebElement(children[i])
if(WebUI.verifyElementHasAttribute(childTestObject, 'checked', 10, FailureHandling.OPTIONAL)){
return childTestObject
}
}
}
This is the helper method that I use for converting a WebElement to a TestObject :
public TestObject getTestObjectFromWebElement(WebElement element) {
TestObject object = new TestObject()
object.addProperty("xpath", ConditionType.CONTAINS, getXPathFromElement(element))
return object
}
Helper for getting xpath from WebElement :
protected String getXPathFromElement(WebElement element) {
String elementDescription = element.toString();
return elementDescription.substring(elementDescription.lastIndexOf("-> xpath: ") + 10, elementDescription.lastIndexOf("]"));
}
Am I missing something here or is there something wrong with the WebElement -> TestObject conversion? Also is this possible using only TestObject or only WebElement? If I could get child TestObjects containing certain attributes from a parent TestObject then I wouldn't need to make a mess using WebElements.
Edit
Another image of the HTML, this time with the first radio button checked. As you can see the second radio button no longer has the 'checked' attribute.
To retrieve the WebElement that is currently checked you can use either of the following Locator Strategies:
cssSelector:
WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.a-toggle.a-toggle--anycase#config-src-laserunits div[id^='config-src-laserunits-']>input.a-toggle__radio[checked]")));
xpath:
WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='a-toggle a-toggle--anycase' and #id='config-src-laserunits']//div[starts-with(#id, 'config-src-laserunits-')]/input[#class='a-toggle__radio' and #checked]")));
I was able to fix this by changing (".//*") to (".//*[#checked='checked']")
parentWebElement.findElement(By.xpath(".//*[#checked='checked']")
will find the element that has the attribute checked = 'checked'
Notice that a list is no longer needed as there can only be 1 checked radio button at a time.
Implementation
public TestObject getCheckedTestObjectFromParent(String parentID){
WebDriver driver = DriverFactory.getWebDriver()
WebElement parentWebElement = driver.findElement(By.id(parentID))
//there is only 1 checked child at a time, so there is no need for a list
WebElement checkedChild = parentWebElement.findElement(By.xpath(".//*[#checked='checked']"))
//convert the WebElement to a TestObject and return
return getTestObjectFromWebElement(checkedChild)
}
Try this Xpath
"//input[#id='config-src-laserunits-wavnmradio' and #checked='checked']"
Example:
List<WebElement> children = driver.findElements(By.xpath("//input[#id='config-src-laserunits-wavnmradio' and #checked='checked']"))
It should return size 1
EDIT
List<WebElement> children = driver.findElements(By.xpath("//input[#id='config-src-laserunits-wavnmradio']"));
for (int i=0;i<children.size();i++)
{
if(children.get(i).getAttribute("checked")!=null)
{
System.out.println("radio button is checked");
}
}

Getting value from tooltip when hover on svg element on the graph created with highcharts

I want to get text/value from the tooltip which appears when hover on svg element on the graph created with highcharts.
Below is the snippet:
Tried below code:
List<WebElement> Volumelist=driver.findElements(By.xpath("//*[name()='svg']//*[name()='g'][5]//*[name()='g'][2]//*[name()='path']"));
System.out.println("Got the list!");
new Actions(driver).moveToElement(Volumelist.get(1)).clickAndHold().build().perform();
WebElement toolTip=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#class='highcharts-halo highcharts-color-3'][#visibility='visible']")));
System.out.println("toolTip text= "+toolTip.getText());
First hover on the element on which tooltip appears and then execute :
String tooltipText = driver.findElement(By.cssSelector("g.highcharts-tooltip text tspan")).getAttribute("textContent");
You can ping me at sandpdangi13#gmail.com if that does not work for you.
Try to hover to tooltip element using this method if normal Actions hover is not working :
public static void mouseHoverJScript(WebDriver driver, WebElement element) {
String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false);"
+ " arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
((JavascriptExecutor) driver).executeScript(mouseOverScript,
element);
I found over their examples page the values with this XPath:
driver.findElement(By.xpath(.//*[name()="g" and contains(#class,"highcharts-label")]//*[name()="tspan" and #style='font-weight:bold'])).getText();
The first step is move the mouse over one point, for example with this XPath, move to the first point:
WebElement elem = DriverUtils.driver.findElement(By.xpath(.//*[name()='path' and contains(#class, 'highcharts-point highcharts-color')][1]));
new Actions(driver).moveToElement(elem).clickAndHold().build().perform();
I used the Selenium 3.9.0, with previous 3.4.0 version doesn't work for me.
So, solution that worked for me:
WebElement elem = driver.findElement(By.xpath("//[name()='svg']//[name()='g'][5]//[name()='g'][2]//[name()='path'][1]"));
new Actions(driver).moveToElement(elem).clickAndHold().moveByOffset(1, 1).pause(1000).perform();
String text=driver.findElement(By.xpath("//[name()='svg']//[name()='g'][9]//[name()='text'][1]//[name()='tspan'][3]")).getText();

Select a Dropdown value in Selenium Webdriver

I am working on automation with Selenium WebDriver. I need to select a dropdown value but I get an error report.
This is the code I am using:
Select dropdown=new Select(driver.findElement(By.xpath("//*[#id=\"myModal\"]/div/div/div/fieldset/form/div[1]/div[2]/div[4]/div/div/div/div[2]")));
Thread.sleep(30000);
dropdown.selectByIndex(2);
But I get this error: Element should have been "select" but was "div"
I will provide code with pageObject design
public class PageWithSelector{
// initialise element first from element than to selector //
#FindBy(id = "selectID")
private WebElement selectorElement;
private Select selector;
public PageWithSelector(WebDriver driver) {
super(driver);
this.webDriver = driver;
//in constructor init elements and also Select control//
PageFactory.initElements(driver, this);
selector = new Select(selectorElement);
}
// selector via text //
public PageWithSelector selectFromSelectorText(String selectorItemText){
selector = new Select(selectorElement);
selector.selectByVisibleText(facility.getName());
return this;
}
// selector via index //
public PageWithSelector selectFromSelectorIndex(int index) {
selector = new Select(selectorElement);
selector.selectByIndex(index);
return this;
}
}
You have to only initialise Select (object) properly.
After click on drop down you can use this code :
List<WebElement> options = driver.findElements(by.xpath(" your locator"));
for(WebElement element : options){
if(element.getText().equals(" your value from drop down")){
element.click();
}
}
I often use a workaround on that.
type inside the combobox the value you want to select and then automate an ENTER Keypress in the combobox.
Now the value is selected in the combobox.
Optional you also can use the Arrowkeys to navigate in the combobox.
driver.findElement(By.xpath("...")).sendKeys("Something you want to choose");
driver.findElement(By.xpath("...")).sendKeys(Keys.DOWN);
driver.findElement(By.xpath("...")).sendKeys(Keys.ENTER);
Hope this helps!

C# selenium Not able to locate table(highlighted in the table) to to perform click action. PFA screenshot of elements page below here with code sippet

Screenshot of elements present in web page
_driver.SwitchTo().DefaultContent();
IWebElement item = FindElement(By.Id("__gadget_4"));
_driver.SwitchTo().Frame(item);
elements = FindElements(By.TagName("iframe"));
foreach (var frame in elements)
{
_driver.SwitchTo().Frame(frame);
item = FindElement(By.Id("treeview-1027-record-8"));
if (item != null)
{
item.Click();
}
}
I don't know why you are using loop just goto frame and click element
_driver.SwitchTo().DefaultContent();
IWebElement FrameName= FindElement(By.Id("__gadget_4"));
_driver.SwitchTo().Frame(FrameName);
item = FindElement(By.Id("treeview-1027-record-8"));
item.Click();
Also as #Shoaib Akhtar says you can directly use name to switch to frame, Also you can use xpaths
IWebElement FrameName= FindElement(By.Xpath("//iframe[#name='__gadget_4']"));
_driver.SwitchTo().Frame(FrameName);
OR
IWebElement FrameName= FindElement(By.Xpath("//iframe[#id='__gadget_4']"));
_driver.SwitchTo().Frame(FrameName);
Directly switch to child frame and then perform action on element you want. Just try this code & check
WebElement wb = _driver.FindElement(By.xpath("//div/iframe[#id"__gadget_2"]"))
_driver.SwitchTo().Frame(wb);
_driver.FindElement(By.Id("treeview-1027-record-8")).Click();

Find text with Selenium in Chrome

How can I get the text 200 in this case:
<p style="margin:0">
You can get <big class="tooltip">200</big> more</p>
I'm trying using:
ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.XPath("//*[contains(#class, 'tooltip')]"));
But can not get the text because the .Text property returns an empty string :(
Any thoughts?
You are using ClassName() with Xpath
ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.Xpath("//*[#class=\"tooltip\"]/big"));
However, I would use CssSelector in this case since css is always preferred over xpath
ReadOnlyCollection<IWebElement> list = _driver.FindElements(By.CssSelector("big.tooltip"));
Considering the element is not inside any iframe since it is not throwing any error, I am assuming the wait is needed. Try the following
By byCss = By.CssSelector("big.tooltip");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(byCss);
});
var text = myDynamicElement.Text;
Looks the element is hidden. So JavaScript is probably your best try.
var text = ((IJavaScriptExecutor)driver).ExecuteScript("return document.querySelector('.tooltip_health_limit').innerHTML;") as string;
To get the text after you find the element:
string text = currentElement.Text;