Selenium Other ways to find_element for onclick

Question:

I am looking at a table that has this <tr onclick="setValue('115751')" role="row" class="odd"> like shown below. I am trying use Selenium to find_element and click on distinct rows based on the setValue. Since I normally use xpath I tried to use that but xpath does not work because some times the order changes.

my_item = '//*[@id="resulttable"]/tbody/tr[1]'
mychoice = driver.find_element(By.XPATH, my_item)
mychoice.click()

How do I get the selenium to click my_item based on the setValue or on the "Recordation No" shown in the table?
I have a little demo content from the website below.

table, th, td {
  border: 1px solid;
}

<table width="100%" class="display dataTable no-footer" id="resulttable" cellspacing="0" role="grid" aria-describedby="resulttable_info" style="width: 100%;">
<thead>
<tr role="row">
<th>Statement</th>
<th>Recordation No</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr onclick="setValue('115751')" role="row" class="odd">
<td>2022-3301051</td>
<td class="hidden-xs hidden-sm sorting_1">
3301051</td>
<td>Submitted</td>
</tr>
<tr onclick="setValue('115529')" role="row" class="even">
<td>2022-3301053</td>
<td class="hidden-xs hidden-sm sorting_1">
3301053</td>
<td>Submitted</td>
</tr>
<tr onclick="setValue('115201')" role="row" class="odd">
<td>2022-3301309</td>
<td class="hidden-xs hidden-sm sorting_1">
3301309</td>
<td>Not Submitted</td>
</tr>
<tr onclick="setValue('115893')" role="row" class="even">
<td>2022-3301310</td>
<td class="hidden-xs hidden-sm sorting_1">
3301310</td>
<td>Not Submitted</td>
</tr>
<tr onclick="setValue('115497')" role="row" class="odd">
<td>2022-3301313</td>
<td class="hidden-xs hidden-sm sorting_1">
3301313</td>
<td>Not Submitted</td>
</tr>
</tbody>
</table>

Asked By: Shane S

||

Answers:

When specifying based on the onclick of the tr tag, you will have to escape the quotes so the xpath would look like this

my_item = "//tr[@onclick="setValue('115497')"]"

or

my_item = "//tr[@onclick='setValue('115497')']"

in case you want to put the variables directly into the string literal:

value = 115497
my_item = f"//tr[@onclick="setValue('{value}')"]"
// or my_item = f"//tr[@onclick='setValue('{value}')']"
Answered By: TamTam
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.