如何使用XPath只选择可见元素? [英] How do I select only visible elements using XPath?
问题描述
I have a GWT application for which I'm trying to write some tests using Selenium.
我使用XPath来识别页面上的元素为测试。使用 id
不会起作用,因为GWT会自动生成 id
值并可以更改。事情开始顺利,当我意识到我可以通过标签找到按钮,如下所示:
I'm using XPath to identify the elements on the page for the tests. Using id
won't work as the id
values are auto-generated by GWT and can change. Things started going well when I realised I could find buttons by their labels as follows:
//button[.='OK']
但是,当我开始运行多个测试时,我开始出现问题。我意识到问题是一旦由Javascript生成的GWT应用程序的所有不同页面都保留在隐藏的< div>
元素的HTML中。这意味着我的Selenium测试有时会单击隐藏的按钮,而不是当前视图中显示的按钮。
However, when I started running multiple tests I started having problems. I realised that the issue was all the different "pages" of the GWT app once generated by the Javascript remain in the HTML in hidden <div>
elements. This meant my Selenium tests were sometimes clicking hidden buttons instead of the button visible in the current view.
使用 Firebug ,看来GWT通过添加 display:none隐藏
到它们的< div>
元素样式
属性。这意味着我可以找到所有隐藏的确定按钮,如下所示:
Examining the HTML with Firebug, it seems that GWT hides the <div>
elements by adding display: none
to their style
attribute. This means I can find all the hidden OK buttons as follows:
//div[contains(@style,'display: none')]//button[.='OK']
这会找到所有隐藏的确定按钮,即在<$ code>< div> 中隐藏的祖先<
This will find all the hidden OK buttons, i.e the buttons which have an ancestor <div>
which is hidden by having display: none
in the style
.
我的问题是:如何使用XPath找到可见的OK按钮?如何在<$ c>中找到 display:none
的按钮$ b $ style $
My question is: how do I use XPath to find only the visible OK buttons? How do I find the buttons which have no ancestor <div>
elements with display: none
in the style
?
推荐答案
b $ b
.//button[.='OK' and not(ancestor::div[contains(@style,'display:none')])
and not(ancestor::div[contains(@style,'display: none')])]
编辑:
以下简单高效的表达式:
The simpler and more efficient expression below:
//div[not(contains(@style,'display:none'))]//button[.='OK']
无法正常工作,因为每个按钮至少有一个div在其祖先中可见。
does not work properly because every button has at least one div that's visible in its ancestors.
这篇关于如何使用XPath只选择可见元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!