JohnSink
JohnSink

Reputation: 143

How to get element by xpath and inner text?

I am trying to locate a UI popup using xpath and inner text. The popup html is like this:

Hello ? {some elements} What would you like to do today {more elements} Play or Die ? {Yes button, No button}.

I want to get this element by using something like this:

//div[contains(@innerText, 'Hello ? What would you like to do today Play or Die ?')]

How do I do this ? Or is there a better way to find this popup ? There are no Ids or permanent classes here. Moreover the DOM structure is variable.

Upvotes: 0

Views: 2322

Answers (2)

har07
har07

Reputation: 89285

Assuming that the interleaving elements contain no inner text, you can use . instead of @innerText to get concatenation of all text nodes within context element (the div in this case). Combine . with normalize-space() to remove leading and trailing whitespace characters, as well as to normalize consecutive whitespace characters into single space. With normalize-space() the . can be removed as it is the default parameter :

//div[contains(normalize-space(), 'Hello ? What would you like to do today Play or Die ?')]

Upvotes: 1

Dekel
Dekel

Reputation: 62536

You should be able to use xpath ver2's matches function:

//div[matches(text(), 'Hello ?\w+ What would you like to do today \w+')]

Which allows regex.

Upvotes: 3

Related Questions