Friday, March 3, 2017

Selenium WebDriver – Working with child element of a table (C#)

Until now we worked with simple tables that allow us to perform all operation without any major challenges. However, in some projects, you will face tables that possess child elements that dynamically created based on user operations, therefore we will need to use some advanced strategies to locate child elements using XPath and CSS.
תוצאת תמונה עבור ‪selenium webdriver ‬‏

To demonstrate the code examples, we will use the following HTML table:  





HTML Code:

<!DOCTYPE html><html><head><title>Locating child elements</title></head> <body><table border="1" width="50%">
<tr> <td>UserID_1 </td>
<td><a href="mailto:X@mail.com">Tzemach@mail.com</a></td> <td><div>
<label for="TMPID_Premium Contract">Premium Contract</label>
<input type="checkbox" id=" TMPID1 _Premium Contract" checked="true"/>
 <label for=" TMPID _Basic Contract">Basic Contract</label>
<input type="checkbox" id=" TMPID1 _Basic Contract" />  </div> </td> </tr>

 <tr> <td>UserID_2 </td>
<td><a href="mailto:Y@mail.com">David@mail.com</a></td> <td><div>
<label for="SeleniumWebDriver_Premium Contract">Premium Contract</label>
<input type="checkbox" id=" TMPID2 _Premium Contract" "/>
<label for=" TMPID _Basic Contract">Basic Contract</label>
<input type="checkbox" id=" TMPID2 _Basic Contract" checked="true"/>
 </div> </td> </tr> </table></body></html>

As you can see from the HTML snippet, the user ID is not static and Therefore we cannot use the regular locator strategies (The ID attribute cannot be associated to a user), to overcome this issue we can us the XPath and CSS selectors in the following way: 

Example:
Checkbox validation (if/else).
We will remove the "Premium Contract" checkbox.
We will check the "Basic Contract" checkbox.
We will validate that the "Basic Contract" is checked.

XPath

Checkbox = Firefox.FindElement(By.XPath("//td[contains(text(),'UserID_1')]/following-sibling::td/descendant::div/label [contains(text(),'Premium')]/following-sibling::input"));
if (Checkbox.Selected == true)
{Checkbox.Click();}
else{//Do something}

Checkbox =Firefox.FindElement(By.XPath("//td[contains(text(),'UserID_1')]/following-sibling::td/descendant::div/label [contains(text(),'Basic')]/following-sibling::input"));
Checkbox.Click();
Assert.IsTrue(Checkbox.Selected);

CSS

We can perform the same task with the CSS selector using the following syntax:

Checkbox = Firefox.FindElement(By.CssSelector("td:contains('UserID_1')+td+td>div>label:contains ('Premium')+input"));

It's may seem complicated so let’s break it to small pieces:

"td:contains('UserID_1') = identify the requested user.
"td:contains('UserID_1')+td+td = This is where the child element is located          
"td:contains('UserID_1')+td+td>div>label:contains ('Premium')+input = Identifying the label with the requested option.

Result:


No comments:

Post a Comment

My Presentations