pjd
pjd

Reputation: 1173

Using Ruby and watir-webdriver, how does one get the XPath of an element if the text is known?

Using watir-webdriver, I am trying to click the "down" button next to some known text on the screen (in this case, "An Example"). When I click the down button, the text itself will move down a list of arbitrary length. I don't always know where the text will appear in the list, and also there is no ID on the text or the down button to uniquely identify the location to click. The button has a class attached ("rowDown down"), but as there can be multiple rows of text, the button class is not unique.

In situations where I can't get get a unique ID, I always turn to XPath.

In this case, I know the XPath of the text I care about will end with /div[2] and the button I want to click is in div[1], more specifically the button I want will have XPath ending in div[1]/button[2]

The question is, how do I get the XPath for the text using watir-webdriver? (An example of the full XPath I could be dealing with is "//*[@id='sortOrder0']/tbody/tr[2]/td[1]/div[2]".) Alternately, and equally acceptable, is there some other, reliable way of getting to the button I care about?

Here is the relevant portion of my HTML, which produces an up arrow and a down arrow next to the words "An Example":

<div>
  <button class="rowUp up"></button>
  <br />
  <button class="rowDown down"></button>
</div>
<div>
  An Example
</div>

Upvotes: 0

Views: 2087

Answers (1)

Justin Ko
Justin Ko

Reputation: 46846

You can check the text of node during an XPath using text(). Therefore you could write an XPath that finds the div with text "An Example", goes to the preceding div and then clicks the down button:

browser.button(xpath: '//div[normalize-space(text())="An Example"]
                        /preceding-sibling::div[1]
                        /button[contains(@class, "rowDown")]').click

Personally I find this hard to read and error prone. I prefer to use basic locators and leave the XPath generation to Watir-Webdriver's internals. A similar effect to the XPath can be achieved with:

browser.div(text: 'An Example').parent.button(class: 'rowDown').click

Upvotes: 1

Related Questions