我正在尝试使用Selenium测试一个复杂的JavaScript接口(使用Python接口,并且跨多个浏览器)。我有一些表单的按钮:
<div>My Button</div>
我希望能够搜索基于“我的按钮”(或不区分大小写,部分匹配,如“我的按钮”或“按钮”)的按钮。
我发现这非常困难,以至于我觉得我遗漏了一些显而易见的东西。到目前为止,我得到的最好的东西是:
driver.find_elements_by_xpath('//div[contains(text(), "' + text + '")]')
但是,这是区分大小写的。我尝试过的另一件事是遍历页面上的所有div,并检查element.text属性。然而,每次你得到一种形式的情况:
<div class="outer"><div class="inner">My Button</div></div>
div.outer的文本也是“我的按钮”。为了解决这个问题,我试着查看div.outer是否是div.inner的父对象,但是我不知道怎么做(element.get_element_by_xpath('..') )返回一个元素的父元素,但它的测试结果不等于div.outer)。
此外,遍历页面上的所有元素似乎真的很慢,至少使用Chrome webdriver是如此。
想法?
我在这里询问(并回答)了一个更具体的版本:
发布于 2013-09-09 22:54:21
尝试以下操作:
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
发布于 2012-09-08 02:44:24
您可以尝试XPath表达式,如下所示:
'//div[contains(text(), "{0}") and @class="inner"]'.format(text)
发布于 2018-12-17 18:18:10
//*将查找任何HTML标记。其中,如果Button和div标签的一些文本是通用的,并且如果//*是类别,那么它将不会像预期的那样工作。如果你需要选择任何特定的元素,那么你可以通过声明HTML元素标签来获得它。像这样:
driver.find_element_by_xpath("//div[contains(text(),'Add User')]")
driver.find_element_by_xpath("//button[contains(text(),'Add User')]")
https://stackoverflow.com/questions/12323403
复制相似问题