Python: Selenium xpath to find element with case insensitive characters?

Question:

I am able to do this

search = "View List"
driver.find_elements_by_xpath("//*/text()[normalize-space(.)='%s']/parent::*" % search)

but I need it to ignore and match all elements with text like: “VieW LiSt” or “view LIST”

search = "View List"
driver.find_elements_by_xpath("//*/lower-case(text())[normalize-space(.)='%s']/parent::*" % search.lower())

The above doesn’t seem to work. lower-case() is in XPATH 1.0

Asked By: I Love Python

||

Answers:

The lower-case() function is only supported from XPath 2.0. For XPath 1.0 you will have to use translate().

Example code is given in this stackoverflow answer.

Edit:
The selenium python bindings site has a FAQ – Does Selenium 2 supports XPath 2.0 ?:

Ref:
http://seleniumhq.org/docs/03_webdriver.html#how-xpath-works-in-webdriver

Selenium delegate XPath queries down to the browser’s own XPath
engine, so Selenium support XPath supports whatever the browser
supports. In browsers which don’t have native XPath engines (IE
6,7,8), Selenium support XPath 1.0 only.

Answered By: Faiz

Since lower-case() is only supported in 2.0 I came up with this solution using translate() so I don’t need to type the whole function manually everytime

translate = "translate({value},'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')"

driver.find_elements(By.XPATH, f"//*/{translate.format(value='text()')}[normalize-space(.)='{search.lower()}']/parent::*")

Which computes to:

>>> print(f"//*/{translate.format(value='text()')}[normalize-space(.)='{search.lower()}']/parent::*")
"//*/translate(text(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')[normalize-space(.)='view list']/parent::*"

Answered By: Oenomaus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.