Find Element Next to Element With Specified Text

A. Duff

The Context

I'm writing Selenium tests for an app which allows the user to submit data on a form and have it displayed in a table. The table is optimistically updated via Javascript/AJAX, and its entries are displayed alphabetically, so there is no guarantee about what position the newly-created element will be in. Therefore, the only way for the tests to identify which element it is is to search by text with something like waitForText.

The element with the identifying text is in its own td element. A sibling td element contains a menu button that I want the tests to click on. The menu options are specific to the newly-created element, so I need to be sure the test is clicking on the one next to the element it just created, not any of the other menu buttons that are next to the other elements in the table.

The Code

<table>
  <tr>
    <td>Element 1 name</td>
    <td>Element 1 extra-data</td>
    <td>Element 1 more-data</td>
    <td onClick='/* display menu for Element 1 */'>Element 1 menu</td>
  </tr>
  <tr>
    <td>Element 2 name</td>
    <td>Element 2 extra-data</td>
    <td>Element 2 more-data</td>
    <td onClick='/* display menu for Element 2 */'>Element 2 menu</td>
  </tr>
  <tr>
    <td>Element 3 name</td>
    <td>Element 3 extra-data</td>
    <td>Element 3 more-data</td>
    <td onClick='/* display menu for Element 3 */'>Element 3 menu</td>
  </tr>
  <tr>
    <td>New element name</td>
    <td>New element extra-data</td>
    <td>New element more-data</td>
    <td onClick='/* display menu for New element */'>New element menu</td>
  </tr>
</table>

I understand it would be better if I could attach an ID or class to the tr containing the new element; however, this is not possible because this ID would best be the internal database ID of the element that was created, which my tests would not have access to. I specifically need the tests to be able to identify the element it created, and all the test knows is what it typed for the name into the form before it clicked Submit.

How can I write a selector that will select that menu button specifically? For example, find_elements_by_xpath("//tr/td[@text='New element']/ /* how do you specify a sibling and not a child here? */")

Javitronxo

You can specify the sibling in the XPath with:

find_elements_by_xpath("//tr/td[@text='New element']/following-sibling::td[1]")

You can read more about it here.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related