I would like to find any WebElement based on text using XPath.
WebElement that I am interested to find,
Its HTML,
Basically my WebElement that I am trying to retrieve by Text contains an input element.
I currently use,
driver.findElement(By.xpath("//*[normalize-space(text()) = 'Own Hotel']"));
which does not find the WebElement above, but it usually works to retrieve all other web elements.
Even,
By.xpath("//*[contains(text(),'Own Hotel')]")
did not give me any results. Although I am interested in exact text match.
I am looking for a way to find web element by text immaterial of the elements that are present inside the web element. If text matches, it should return the WebElement.
Thanks!
It seems text is wrapped inside a label and not input. Try this
There is nice explanation about this xpath pattern here
In the HTML below:
The innerText Own Hotel within the
<input>
node contains a lot of white-space characters in the beginning as well at the end. Due to the presence of these leading and trailing white-space characters you can't use the location pathtext()
as:As an alternative, you need to use the String Function
string normalize-space(string?)
as follows:However, it would a better idea to make your search a bit more granular adding the tagName and preferably an unque attribute as follows:
Using tagName and
normalize-space()
:Using tagName, and
normalize-space()
:References
you can find a couple of relevant discussions using normalize-space() in: