Winterflags Winterflags - 25 days ago 8
Python Question

XPath: Translate into lowercase and simultaneously Normalize-space

I'm using Selenium with Firefox for Selenium. I want to match an Element on a page containing a certain Text; and so I need the driver to recognize the text on the page in lower-case characters, so it matches with my string keyword

searchkey.lower()
.

I've attempted to use the
translate()
function in XPath, but I simultaneously want to
normalize-space()
to get rid of any whitespace problems.

Can these two functions be combined into one XPath string?

I tried the XPath below, and some other variants, but wasn't able to make a match with Selenium's
driver.find_element_by_xpath(my_xpath)
:


my_xpath = "//a[contains(translate(normalize-space(.), '%s', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'))]" % searchkey.lower()"



or as a one-line code block:

my_xpath = "//a[contains(translate(normalize-space(.), '%s', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'))]" % searchkey.lower()"





Further explanation:



For testing purposes, we can pretend that
searchkey = "MY STRING"
, and that
searchkey.lower()
would return
"my string"
.

And the Element on the page that I want to match, might contain the Text
" mY sTrinG "
. And so I want XPath to translate the characters to lowercase and remove excess whitespaces of any kind, therefore matching with the above
"my string"
.

Answer Source

Your though process is correct but the xpath has a minor issue. You won't pass expected text to the translate function, you will pass it to the contains function, so it can test if it is there or not

my_xpath = "//a[contains(translate(normalize-space(.), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]" % searchkey.lower()"