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

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

问题描述

我正在尝试使用Selenium测试复杂的javascript界面​​(使用Python界面,并跨多个浏览器).我有许多形式的按钮:

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 + '")]')

但是,这是区分大小写的.我尝试过的另一件事是遍历页面上的所有div,并检查element.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还具有我的按钮"作为文本.为了解决这个问题,我尝试查看div.outer是否是div.inner的父级,但无法弄清楚该怎么做(element.get_element_by_xpath('..')返回元素的父级,但是测试不等于div.outer).另外,至少使用Chrome网络驱动程序迭代页面上的所有元素似乎真的很慢.

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 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.

想法?

这个问题有点模糊.在此处询问(并回答)一个更具体的版本:

This question came out a little vague. Asked (and answered) a more specific version here: How to get text of an element in Selenium WebDriver (via the Python api) without including child element text?

推荐答案

尝试以下操作:

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

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

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