简体   繁体   English

Python: Selenium xpath 查找不区分大小写字符的元素?

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

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"但我需要它忽略所有元素并将其与文本匹配,例如:“VieW LiSt”或“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 lower-case()在 XPATH 1.0

The lower-case() function is only supported from XPath 2.0. 只有XPath 2.0支持lower-case()函数。 For XPath 1.0 you will have to use translate() . 对于XPath 1.0,您将不得不使用translate()

Example code is given in this stackoverflow answer . stackoverflow答案中给出了示例代码。

Edit: The selenium python bindings site has a FAQ - Does Selenium 2 supports XPath 2.0 ? 编辑:selenium python绑定站点有一个FAQ - Selenium 2是否支持XPath 2.0? :

Ref: http://seleniumhq.org/docs/03_webdriver.html#how-xpath-works-in-webdriver 参考: 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. Selenium委托XPath查询浏览器自己的XPath引擎,因此Selenium支持XPath支持浏览器支持的任何内容。 In browsers which don't have native XPath engines (IE 6,7,8), Selenium support XPath 1.0 only. 在没有本机XPath引擎的浏览器中(IE 6,7,8),Selenium仅支持XPath 1.0。

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由于lower-case()仅在 2.0 中受支持,因此我使用translate()想出了这个解决方案,因此我不需要每次都手动输入整个 function

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::*"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM