如何在 Selenium WebDriver (Python) 中找到包含特定文本的元素? [英] How do I find an element that contains specific text in Selenium WebDriver (Python)?

查看:86
本文介绍了如何在 Selenium WebDriver (Python) 中找到包含特定文本的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Selenium 测试复杂的 JavaScript 界面(使用 Python 界面并跨多个浏览器).我有许多表单按钮:

我的按钮

我希望能够根据我的按钮"搜索按钮;(或不区分大小写的部分匹配项,例如我的按钮"或按钮").

我发现这非常困难,以至于我觉得我错过了一些明显的东西.到目前为止,我拥有的最好的事情是:

driver.find_elements_by_xpath('//div[contains(text(), "' + text + '")]')

然而,这是区分大小写的.我尝试过的另一件事是遍历页面上的所有 div,并检查 element.text 属性.但是,每次得到表单的情况:

我的按钮

div.outer 也有我的按钮";作为文本.为了解决那个,我试图查看 div.outer 是否是 div.inner 的父级,但我不知道如何做到这一点 (element.get_element_by_xpath('..') 返回一个元素的父元素,但它测试不等于 div.outer).

此外,遍历页面上的所有元素似乎真的很慢,至少使用 Chrome 网络驱动程序是这样.

想法?


我在这里询问(并回答)了一个更具体的版本:如何在Selenium WebDriver 中获取元素的文本,而不包含子元素文本?

解决方案

尝试以下操作:

driver.find_elements_by_xpath("///*[contains(text(), 'My Button')]")

I'm trying to test a complicated JavaScript interface with Selenium (using the Python interface, and across multiple browsers). I have a number of buttons of the form:

<div>My Button</div>

I'd like to be able to search for buttons based on "My Button" (or non-case-sensitive, partial matches such as "my button" or "button").

I'm finding this amazingly difficult, to the extent to which I feel like I'm missing something obvious. The best thing I have so far is:

driver.find_elements_by_xpath('//div[contains(text(), "' + text + '")]')

This is case-sensitive, however. The other thing I've tried is iterating through all the divs on the page, and checking the element.text property. However, every time you get a situation of the form:

<div class="outer"><div class="inner">My Button</div></div>

div.outer also has "My Button" as the text. To fix that, I've tried looking to see if div.outer is the parent of div.inner, but I couldn't figure out how to do that (element.get_element_by_xpath('..') returns an element's parent, but it tests not equal to div.outer).

Also, iterating through all the elements on the page seems to be really slow, at least using the Chrome webdriver.

Ideas?


I asked (and answered) a more specific version here: How to get text of an element in Selenium WebDriver, without including child element text?

解决方案

Try the following:

driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")

这篇关于如何在 Selenium WebDriver (Python) 中找到包含特定文本的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆