Clicking all elements with matching class - selenium

I'm new to Selinium. There is a table (inside another table) that I want to click each <td>click here</td> with a matching class value (note the text between opening and closing td will change but is irrelevant for matching purposes). The class value I'm trying to match is open. From here I learn the right way is with //*[contains(concat(" ", normalize-space(#class), " "), " open ")]
This seems to work but just for one random cell. How do I make it click all? I was planning on accomplishing this first and repeating the step, but it may be worth noting that the script should also do the same for class value available and not just open Is there away to do logical or?
TL;DR I want to click everything with <td class="open">...</td>
and
<td class="available">...</td> where ... is example text that will vary but should be ignored.

Get all elements and store them in a List, then iterate over them and click the buttons in sequence.
List<WebElement> list = driver.findElements(By.xpath("//*[contains(concat(" ", normalize-space(#class), " "), " open ")]"));
for(WebElement webelement : list) {
// webelement Click the button here
}

To get all elements, you should use driver.FindElements. Make sure it's what you used, not driver.FindElement?

Use following approach may help you -
List<WebElement> allElements = driver.findElements(By.tagName("td"));
for(WebElement element:allElements)
{
if(element.getAttribute("class").contains("open"))
{
// manipulate with <td> tag data
}
}

Please use following XPath:
//td[normalize-space(#class)="open" or normalize-space(#class)="available"]
This should match both <td class=" open ">...</td> and
<td class=" available ">...</td>

Related

Not able to Enter Text in a TextBox using Selenium Webdriver

I have a TextBox that appears on Radio Button Selection and I have to enter values in a particular format(XYZ989898-99). However I am unable to do so by using the commonly used methods of entering text in selenium.
Background info related to Textbox :
TextBox appears when user clicks on Yes radio button.
TextBox has default value as XYZ already entered.
SendKeys do not concatenate the text given without XYZ as well.
TextBox is inside an Iframe to which focus is shifted correctly.
The code does not fail, it just remained clicked on textbox without entering anything.
Approach 1 :
driver.findElement(locator).SendKeys("989898-99");
Approach 2 :
driver.findElement(locator).clear();
driver.findElement(locator).SendKeys("XYZ989898-99");
Approach 3 :
WebElement element = driver.findElement(locator);
Actions action1 = new Actions(driver);
action1.movetoElement(element).click().perform();
action1.sendKeys("XYZ989898-99");
HTML Sample :
<div class="value" ng-show="selectedValue" style="">
<label class="labelAboveTextBox">XYZ Number*</label>
<input type="text" class="Value" ng-model="XYZNumber" ng-
req="XYZNumber" xyz-input="" maxlength="12" style="value"
id="value" value="XYZ" required="required">
<!-- ngIf: invalidtspmessage -->
<span style="font-family: 'NeueHaasGroteskText';font-size:
0.7rem;color: black;">
Note: Enter XYZ is this format: XXXXXXXXX-XX
</span>
</div>
I would like to know If there is any other approach that can be used to get this problem resolved and also why does the above approaches failed to work.
You have used the wrong methods for sending the keys. (in approach 1 and 2)
Instead of .SendKeys(), you have to use .sendKeys() method for writing anything on UI side
Into the third approach, you have used the wrong method .movetoElement(). The method name is .moveToElement().
For sendKeys() don't need to use Actions class. basically, it is for Keyboard events and for mouse events.
(WebElement).sendKeys("989898-99"); // first approach you can use
(WebElement).clear(); // second approach you can use
(WebElement).sendKeys("XYZ989898-99");
Hope this will help you to solve your errors.
Other way you can use is to set the text is by using the JavaScriptExecutor. Give some delay before performing the action.
Try the below sample code :
Thread.sleep(3000);
((JavascriptExecutor) driver).executeScript("document.getElementById('value').value='XYZ989898-99';");
As the id is unique, you can use the JavaScript's getElementById() function to set the value.
If you want to set the text through the sendKeys() method and before that if you want to clear the text then simple clear() may not work instead you can try to delete the XYZ values first and try to send the values like below again :
// Wait for some time
Thread.sleep(3000);
// Locate the element first and store it in some variable
WebElement element = driver.findElement(By.id("value"));
// Fetch the existing text from the field first
String existingValue = element.getAttribute("value");
// Wait for some time
Thread.sleep(3000);
// Click on that element first so the focus will shift to there
element.click();
// Wait for some time
Thread.sleep(2000);
// Loop until the existing value length
for(int i=0;i<existingValue.length();i++) {
// Remove the existing character text one by one
element.sendKeys(Keys.BACK_SPACE);
}
// Try to send the text at the end, make sure that you should append XYZ as a prefix
element.sendKeys("XYZ989898-99");
I hope it helps...

Improvement With Xpath Search?

I am a student learning selenium and trying to set a checkbox(by placing a tick) that resides on the same row as a target document. Here is how the row looks:
<span><input>Checkbox</input></span> - <span>_lblDocumentCategoryDescription</span> - <span>_lblDocumentdescription</span>
Each row consists of a checkbox for that row, a category and a description. I am provided the description and need to set the corresponding checkbox at the beginning of the row.
Although I have a solution that works I am looking for a better method as my method is very slow and I can call it multiple times, compounding the slowness. The page in question has 315 fixed different documents that might possibly be added (to a merge and print feature). I usually add at least 3 rows so need to run the search
I am currently using xpath to search since my knowledge of CSS is limited and it seems like traversing up the DOM (no :parent?) is not easy unless using some javascript, which I am trying to avoid. I have read that executing JS doesn't emulate the user correctly so I guess xpath is the solution?
As I know there must be a quicker/better/more efficient solution I am hoping others might have found better?
Here is what I am currently using:
Method Call
CPTools,setStupidCheckbox("Sublease Addendum", true);
Method:
public CPTools setStupidCheckbox(String documentToPrint, Boolean onIfTrue) {
this.log.trace("Starting: setStupidCheckbox; parameter: documentToPrint " + documentToPrint);
String xpathForCheckboxes = "/ancestor::tr//input";
try {
String xpathForDocumentDescriptions = String.format("//span[contains(text(), '%s')]", documentToPrint);
tools.waitForElement(By.xpath(xpathForDocumentDescriptions), 2);
if (driver.findElement(By.xpath(xpathForDocumentDescriptions)).isDisplayed()) {
driver.findElementByXPath(xpathForDocumentDescriptions + xpathForCheckboxes).click();
}
} catch (org.openqa.selenium.NoSuchElementException | ElementNotVisibleException e) {
}
this.log.trace("Ending: setStupidCheckbox");
return this;
}
Here is the full xpath for a table row (the dynamic part of the id is the _ctl316):
<tr class="DataGridCellData">
<td class="DataGridCellDataCenterAligned">
<span class="DataLabel"><input id="ctl01_PageBody_grdDocument_ctl316_chkSelect" name="ctl01$PageBody$grdDocument$ctl316$chkSelect" onclick="javascript:uiHelper.GridCellCheck(this, 'chkAllSelect');" type="checkbox"></span>
</td><td>
<span id="ctl01_PageBody_grdDocument_ctl316_lblDocumentCategoryDescription">Approval Form</span>
</td><td align="left">
<span id="ctl01_PageBody_grdDocument_ctl316_lblDocumentdescription">Sublease Addendum</span>
</td><td align="center">
</td>
</tr>
Thanks in advance for any possible help.
Try below XPath if span text (Sublease Addendum) is unique:
//td[.= 'Sublease Addendum']

How to retrieve the value of an attribute using Seleium WebDriver?

The HTML code is given attached, I do not want to use hard code xpath, the requirement is to make it generic:
<td bgcolor="#FFFFFF">
<input name="hotel_name_0" id="hotel_name_0" type="text" value="Hotel Creek" class="select_text" onfocus="disable_ctrlV()" onkeypress="return Nothingonly(event)">
</td>
Code:
public static boolean fncVerifyTextInColumn(WebElement gridObjWebElement,
String stringToValidate, int columnNumber,String colName) {
boolean flagTextinColumn=false;
ArrayList<WebElement> objRows;
ArrayList<WebElement> objCols;
ArrayList<WebElement> childElement;
objRows=(ArrayList<WebElement>)gridObjWebElement.findElements(By.tagName("tr"));
objCols=(ArrayList<WebElement>)objRows.get(0).findElements(By.tagName("td"));
if(objCols.get(columnNumber).getText().equalsIgnoreCase(colName)){
for(int index=1;index<objRows.size();index++){
objCols=(ArrayList<WebElement>)objRows.get(index).findElements(By.tagName("td"));
childElement=(ArrayList<WebElement>)objCols.get(columnNumber).findElements(By.xpath("//input"));
System.out.println(childElement.get(0).getAttribute("value"));
if(stringToValidate.trim().equalsIgnoreCase(childElement.get(0).getAttribute("value").trim())){
flagTextinColumn=true;
}
}
}
return flagTextinColumn;
}
Method Calling:
fncVerifyTextInColumn(objGrid,hotels,1,"Hotel Name");
I would use cssSelector [id^='hotel_name_'] to locate the element and then getAttribute() retrieve the attribute value
By css = By.cssSelector("[id^='hotel_name_']");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(css));
System.out.println(myDynamicElement.getAttribute("value"));
Notice the regex search of cssSelector here. With ^ I am skipping any dynamic number. Hoping that's the only element with hotel_name_someNumber on the page.
Just do
String attValue = driver.findElement(byAnyMethod).getAttribute("AttributeName");
Hope it helps
I think what you are looking for is this. (I'm assuming you know how to code, you just need a general direction so I'm going to leave out specific code.)
First, find the table the td is in. You might need to use an xPath for this or you'll need to assign an ID to the table so you can locate it.
Then once you have the table, do a FindElements to get the list of TRs under it.
Once you have the TRs, you can loop through them, grab the TDs under that and grab the TD at the index that has the INPUT you want the value of, get the INPUT and then get it's value.
Yep, lots of steps.
A shortcut may be to class all of the inputs you want the value for with a unique class and do a FindElements By className and loop through that list.

How can I select checkboxes using the Selenium Java WebDriver?

How can I check the checkboxes using an id or XPath expression? Is there a method similar to select by visibletext for a dropdown?
Going through the examples given for all other related questions, I could not find a proper solution that works in a concise way that by few line or method I can check a chekbox or radio button.
A sample HTML section is below:
<tbody>
<tr>
<td>
<span class="120927">
<input id="ctl00_CM_ctl01_chkOptions_0" type="checkbox" name="ctl00$CM$ctl01$chkOptions$0"/>
<label for="ctl00_CM_ctl01_chkOptions_0">housingmoves</label>
</span>
</td>
</tr>
<tr>
<td>
<span class="120928">
<input id="ctl00_CM_ctl01_chkOptions_1" type="checkbox" name="ctl00$CM$ctl01$chkOptions$1"/>
<label for="ctl00_CM_ctl01_chkOptions_1">Seaside & Country Homes</label>
</span>
</td>
</tr>
</tbody>
Selecting a checkbox is similar to clicking a button.
driver.findElement(By.id("idOfTheElement")).click();
will do.
However, you can also see whether the checkbox is already checked. The following snippet checks whether the checkbox is selected or not. If it is not selected, then it selects.
if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
driver.findElement(By.id("idOfTheElement")).click();
}
It appears that the Internet Explorer driver does not interact with everything in the same way the other drivers do and checkboxes is one of those cases.
The trick with checkboxes is to send the Space key instead of using a click (only needed on Internet Explorer), like so in C#:
if (driver.Capabilities.BrowserName.Equals(“internet explorer"))
driver.findElement(By.id("idOfTheElement").SendKeys(Keys.Space);
else
driver.findElement(By.id("idOfTheElement").Click();
If you want to click on all checkboxes at once, a method like this will do:
private void ClickAllCheckboxes()
{
foreach (IWebElement e in driver.FindElements(By.xpath("//input[#type='checkbox']")))
{
if(!e.Selected)
e.Click();
}
}
Solution for C#
try
{
IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
if (!TargetElement.Selected)
{
TargetElement.SendKeys(Keys.Space);
}
}
catch (Exception e)
{
}
You can use the following code:
List<WebElement> checkbox = driver.findElements(By.name("vehicle"));
((WebElement) checkbox.get(0)).click();
My HTML code was as follows:
<.input type="checkbox" name="vehicle" value="Bike">I have a bike<br/>
<.input type="checkbox" name="vehicle" value="Car">I have a car<br/>
To get the checkbox for 'Seaside & Country Homes', use this XPath:
//label[text()='Seaside & Country Homes']/preceding-sibling::input[#type='checkbox']
To get the checkbox for 'housingmoves', use this XPath:
//label[text()='housingmoves']/preceding-sibling::input[#type='checkbox']
The principle here is to get the label with the text you want, then get the checkbox that is before the label, since that seems to be how your HTML is laid out.
To get all checkboxes, you would start a little higher up and then work down, so that is to say get the table, and then get any checkbox within a span:
//table/descendant::span/input[#type='checkbox']
I found that sometimes JavaScript doesn't allow me to click the checkbox because was working with the element by onchange event.
And that sentence helps me to allow the problem:
driver.findElement(By.xpath(".//*[#id='theID']")).sendKeys(Keys.SPACE);
This should help -
IWebElement elementToClick = driver.findElement(By.xpath(""//input[contains(#id, 'lstCategory_0')]"));
elementToClick.Click();
You can also pass an id.
If you want something like visible text you can "find element" by name if they have names.
The below code will first get all the checkboxes present on the page, and then deselect all the checked boxes.
List<WebElement> allCheckbox = driver.findElements(By
.xpath("//input[#type='checkbox']"));
for (WebElement ele : allCheckbox) {
if (ele.isSelected()) {
ele.click();
}
}
A solution using WebDriver and C# is below. The key idea is to get the ID of the checkbox from the labels' 'for' attribute, and use that to identify the checkbox.
The code will also set the checkbox state only if it needs to be changed.
public void SetCheckboxStatus(string value, bool toCheck)
{
// Get the label containing the checkbox state
IWebElement labelElement = this.Driver.FindElement(By.XPath(string.Format("//label[.='{0}']",value)));
string checkboxId = labelElement.GetAttribute("for");
IWebElement checkbox = this.Driver.FindElement(By.Id(checkboxId));
if (toCheck != checkbox.Selected)
{
checkbox.Click();
}
}
Maybe a good starting point:
isChecked = driver.findElement((By.id("idOftheElement"))).getAttribute("name");
if(!isChecked.contains("chkOptions$1"))
{
driver.FindElement(By.Id("idOfTheElement")).Click();
}
Running this approach will in fact toggle the checkbox; .isSelected() in Java/Selenium 2 apparently always returns false (at least with the Java, Selenium, and Firefox versions I tested it with).
The selection of the proper checkbox isn't where the problem lies -- rather, it is in distinguishing correctly the initial state to needlessly avoid reclicking an already-checked box.
To select a checkbox, use the "WebElement" class.
To operate on a drop-down list, use the "Select" class.
Step 1:
The object locator supposed to be used here is XPath. So derive the XPath for those two checkboxes.
String housingmoves="//label[contains(text(),'housingmoves')]/preceding-sibling::input";
String season_country_homes="//label[contains(text(),'Seaside & Country Homes')]/preceding-sibling::input";
Step 2:
Perform a click on the checkboxes
driver.findElement(By.xpath(housingmoves)).click();
driver.findElement(By.xpath(season_country_homes)).click();
For a partial match, do the following:
getDriver().findElement(By.cssSelector("<tag name>[id*='id pattern to look for']")).click();
Here is the C# version of Scott Crowe's answer. I found that both IEDriver and ChromeDriver responded to sending a Key.Space instead of clicking on the checkbox.
if (((RemoteWebDriver)driver).Capabilities.BrowserName == "firefox")
{
// Firefox
driver.FindElement(By.Id("idOfTheElement")).Click();
}
else
{
// Chrome and Internet Explorer
driver.FindElement(By.Id("idOfTheElement")).SendKeys(Keys.Space);
}
I tried with various approaches, but nothing worked. I kept getting "Cannot click element" or ElementNotVisibleException.
I was able to find the input, but I couldn't check it. Now, I'm clicking on the div that contains the checkbox and it works with following HTML (CSS based on Bootstrap).
#foreach (var item in Model)
{
<tr>
<td>
<div id="#item.Id" class="checkbox">
<label><input type="checkbox" class="selectone" value="#item.Id"></label>
</div>
</td>
<td val="#item.Id">
#item.Detail
</td>
<td>
<div>#item.Desc
</div>
</td>
<td>
#Html.ActionLink("Edit", "Create", new { EditId = item.Id })
</td>
</tr>
}
This is the code for WebDriver:
var table = driver.FindElement(By.TagName("table"));
var tds = table.FindElements(By.TagName("td"));
var itemTds = tds.Where(t => t.Text == itemtocheck);
foreach (var td in itemTds)
{
var CheckBoxTd = tds[tds.IndexOf(td) - 1];
var val = td.GetAttribute("val");
CheckBoxTd.FindElement(By.Id(val)).Click();
}
In this approach, I give the item id as id for the div and also add an attribute for td with that id. Once I find the td of the item that needs to be checked, I can find the div before that td and click it. We can also use the XPath query that supports before (here is the example http://learn-automation.com/how-to-write-dynamic-xpath-in-selenium/).

Issue selecting Radio button in Selenium Webdriver

<table id="Content_Content_Content_ctlCaseInfo_rdochldplcm" class="fltLeft">
<tr>
<td><input type="radio" id="Content_Content_Content_ctlCaseInfo_rdochldplcm_0" name="ctl00$ctl00$ctl00$Content$Content$Content$ctlCaseInfo$rdochldplcm" value="0" /><label for="Content_Content_Content_ctlCaseInfo_rdochldplcm_0">No</label></td><td><input type="radio" id="Content_Content_Content_ctlCaseInfo_rdochldplcm_1" name="ctl00$ctl00$ctl00$Content$Content$Content$ctlCaseInfo$rdochldplcm" value="1" /><label for="Content_Content_Content_ctlCaseInfo_rdochldplcm_1">Yes</label></td>
</tr>
</table>
When I try
driver.FindElement(By.Id("Content_Content_Content_ctlCaseInfo_rdochldplcm")).Click();
it clicks to "Yes"
When I try driver.FindElement(By.Id("Content_Content_Content_ctlCaseInfo_rdochldplcm_0")).Click();
OR
driver.FindElement(By.Id("Content_Content_Content_ctlCaseInfo_rdochldplcm_1")).Click();
Nothing happens and no radio button gets selected.
Please suggest ways to handle this situation ..thanks a lot!!
It would probably be better to click the Radio buttons through XPath.
In your specific case, the XPath for:
Yes - Radio Button:
"//input[contains(#id, 'rdochldplcm') and contains(#value, 1)]"
No - Radio Button:
"//input[contains(#id, 'rdochldplcm') and contains(#value, 0)]"
In this instance, if you wanted to click the 'Yes' Radio button, you can do this:
string yesRadioButtonXPath = "//input[contains(#id, 'rdochldplcm') and contains(#value, 1)]"
IWebElement yesRadioButton = driver.FindElement(By.XPath(yesRadioButtonXPath));
yesRadioButton.Click();
For the 'No' Radio button, you would use this:
string noRadioButtonXPath = "//input[contains(#id, 'rdochldplcm') and contains(#value, 0)]"
IWebElement noRadioButton = driver.FindElement(By.XPath(noRadioButtonXPath));
yesRadioButton.Click();
Since you're using a table, there may be a chance that the XPath may return more than one element. You'd need to use a different method to sort out the elements in that case, but for what you're looking for, this method should work.
this solved my problem perfeclty
I have a page with 18 radio buttons in 6 groups which represented "Yes" "No" and "No Answer"
I was trying to get them by ID but it was randomized by the app
But using a name and value tags made it work.
radios were defined basically like this:
input value="2" class=" x-form-radio x-form-field" autocomplete="off" id="randID_13578" name="emailNotifiyOptionAllow" type="radio">
and every time i opened this page id was different so using
"//input[contains(#name, 'emailNotifyOptionAllow') and contains(#value, 1)]"
solved it.
Thanx
Use this :
//First get the list of values from the radio button
List < WebElement > elements = driver.findElements(By.cssSelector("table[id='Content_Content_Content_ctlCaseInfo_rdochldplcm'] > td"));
WebElement value;
//use loop for searching the particular element
for(WebElement element : elements){
//Getting the value of the element
value = element.findElement(By.cssSelector("label")).getText();
//condition to click on the element
if(value.trim().equals("No")){ //Here value is hard coded. You can take from excel sheet also
// If condition satisfies, it will click on the element
element.findElement(By.cssSelector("input").click();
}
}
This can be used as a common function also.
try [0] and [1] instead of the underscore.
Try your code with the given below CSS :
Step 1:
By Provided HTML Piece we can derive the CSS of the Radio Button
css=#Content_Content_Content_ctlCaseInfo_rdochldplcm input
Step 2:
Click on the radio button using Web Driver Code
driver.findElement
(By.cssSelector("#Content_Content_Content_ctlCaseInfo_rdochldplcm input"))
.click();