Home > other >  XPath: Find element that contains exact text while doing translate and normalize-space
XPath: Find element that contains exact text while doing translate and normalize-space

Time:12-08

I am unsure about the correct XPath syntax to achieve these objectives:

  • The text content of the element on the web page should be exactly "ABC", except:

  • I want to use translate so that I can search with "abc" and find "ABC"

  • I want to do normalize-space

I know the syntax for translate and normalize-text when using contains, namely:

"//*[contains(translate(normalize-space(.), '%s), '%s')]" % ("ABC', 'abc'", "abc")
 #                                                           ↑ Translation   ↑ Target

This will find an element that contains "ABC" like "ABCD" when searching with "abc".

But, I am struggling with the correct syntax when not using contains, i.e. that the text content has to be exactly "ABC" and not "ABCD" and be found with "abc" – while at the same time performing normalize-space.

I know that you can find an exact text e.g. by using:

//*[normalize-space(text()) = "ABC"]

How do I combine these parts?


NB: I am using Firefox for Selenium to find elements via driver.find_element_by_xpath. As far as I know, Firefox uses XPath 1 and not any later versions of like XPath 2.

CodePudding user response:

You can use or operator within the XPath expression.
So you can use this locator:

//*[normalize-space(text()) = "ABC" or normalize-space(text()) = "abc"]

CodePudding user response:

If you use //*[translate(normalize-space(), 'abc', 'ABC') = 'ABC'] you select elements whose normalized string value is any case version of ABC.

  • Related