Every automation tester should possess the following two skills while developing an automation test script. 1) Getting to know automation tools 2) locating web elements. As an Selenium Testing Services company, we have mitigated several failed Selenium automation testing projects. Most of them failed due to not following test automation best practices, writing absolute XPaths & CSS Selectors. Learning Selenium Tool commands is easy. However, writing robust Selenium locators comes from experience. To help newbie test automation engineers, we have written this blog article with various XPath Examples for HTML Tables.
XPath to locate a table using row count
Sometimes you may need to identify an HTML table using its row count. Using XPath count function, you can find a table using row count. The below table has 6 rows including a row for headers. Let’s see how to identify using its row count.
XPath
//table[count(.//tr)=6]
locate using column count
Locating a table using column count is simple. Just add ‘th’ in the Row count Xpath.
XPath
//table[count(.//tr/th)=4]
Locate Last Row
You no need to use For Loop to identify last row in a table. Use ‘Last’ XPath function to locate last row.
XPath
//table[@id='tbl1']//tr[last()]
Identify Alternate Rows
CSS
table[id='tbl1'] tr:nth-child(2n+1)
Advanced XPath Tricks
Find Data in a Specific Cell
To target a specific cell based on row and column position:
//table[@id='tbl1']//tr[3]/td[2]
Explanation: This XPath locates the data in row 3 and column 2 within the table that has an ID tbl1.
Find a Cell with Specific Text
To locate a cell containing exact text:
//table[@id='tbl1']//td[text()='Sample Data']
Explanation: This XPath targets the ‘td’ element that contains the exact text “Sample Data” in the table with ID tbl1.
Find a Cell with Partial Text
For dynamic content, contains() helps locate text that partially matches:
//table[@id='tbl1']//td[contains(text(),'Sample')]
Explanation: This XPath locates any ‘td’ element that contains the word “Sample” as part of its text.
Conclusion:
Mastering XPath expressions is crucial for effective Selenium automation testing, especially when interacting with HTML tables. By learning to locate tables based on row and column counts, identify specific rows like the last one, and select alternate rows, testers can create more robust and efficient test scripts. At Codoid, we specialize in delivering top-notch automation testing services, ensuring that your applications perform flawlessly across various scenarios. Our expertise in crafting precise XPath expressions and leveraging advanced testing techniques empowers your team to achieve seamless and reliable test automation outcomes.
Comments(0)