如何使用 XPath 仅选择可见元素? [英] How do I select only visible elements using XPath?

查看:36
本文介绍了如何使用 XPath 仅选择可见元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 GWT 应用程序,我正在尝试使用 .

我使用 XPath 来识别页面上的元素以进行测试.使用 id 将不起作用,因为 id 值是由 GWT 自动生成的并且可以更改.当我意识到我可以按如下所示的标签找到按钮时,事情开始进展顺利:

//button[.='OK']

然而,当我开始运行多个测试时,我开始遇到问题.我意识到问题是由 Javascript 生成的 GWT 应用程序的所有不同页面"都保留在隐藏的 <div> 元素中的 HTML 中.这意味着我的 Selenium 测试有时会点击隐藏的按钮,而不是当前视图中可见的按钮.

使用 Firebug 检查 HTML,似乎 GWT 隐藏了

元素通过添加 display: none 到它们的 style 属性.这意味着我可以找到所有隐藏的 OK 按钮,如下所示:

//div[contains(@style,'display: none')]//button[.='OK']

这将找到所有隐藏的 OK 按钮,即具有祖先

的按钮,通过 display: none 中隐藏风格.

我的问题是:如何使用 XPath 只找到可见的 OK 按钮?如何在 style 中找到没有祖先

元素和 display: none 的按钮?

解决方案

这应该有效:

.//button[.='OK' and not(ancestor::div[contains(@style,'display:none')])而不是(祖先:: div [包含(@style,'显示:无')])]

下面更简单有效的表达方式:

//div[not(contains(@style,'display:none'))]//button[.='OK']

无法正常工作,因为每个按钮至少有一个在其祖先中可见的 div.

I have a GWT application for which I'm trying to write some tests using Selenium.

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']

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.

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']

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.

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?

解决方案

This should work:

.//button[.='OK' and not(ancestor::div[contains(@style,'display:none')])
and not(ancestor::div[contains(@style,'display: none')])]

EDIT:

The simpler and more efficient expression below:

//div[not(contains(@style,'display:none'))]//button[.='OK']

does not work properly because every button has at least one div that's visible in its ancestors.

这篇关于如何使用 XPath 仅选择可见元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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