Case Study: A Reliable Test Statement to Locate A Non-Unique Button

There are several ways, commonly people chose a less optimal one. This article shows a stable way, using Powerful XPath.

Courtney Zhan

--

In web test automation, generally speaking, when there is a unique ID for the target element, we use the ID locator. However, at work, the IDs do not exist. This article show how to write a reliable automated step for a common operation where multiple buttons with the same text.

The web page below has several “Like” buttons in a table. BTW, this style of web page layout is fairly common.

Example 1. Button with Unique ID

To locate the “Like” button of TestWise.

The HTML fragment:

<tr>
<td>TestWise</td>
<td><span>2007</span></td>
<td><a href="https://agileway.com.au/testwise">https://testwisely.com/testwise</a></td>
<td><button id="like-testwise">Like</button></td>
</tr>

The automated test step.

Easy: use “ID” because there is one for the button.

  1. Playwright
# Playwright
page.locator("#like-testwise")

2. Selenium WebDriver

driver.find_element(:id, "like-testwise")

Example 2. Button with no unique identifier or attributes

Now try to click the “Like” button for WhenWise, which does not have an ID, or any identifiable attributes.

<tr class="service_products">
<td>WhenWise</td>
<td>2018</td>
<td><a href="https://whenwise.com">https://whenwise.com</a></td>
<td><button>Like</button></td>
</tr>

What is the optimal test statement to locate this button?

Playwright recorder suggestion.

The Playwright recorder suggests this:

page.getByRow('row', {name: 'WhenWise 2018 https://whenwise.com Like'}).
getByRole('button');

It works, but it is no good because it is fragile. Consider the possible changes that programmers might make in the future:

  • Text Correction, e.g. “2018” => “2019”

--

--