How do I select only visible elements using XPath?
Solution 1
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.
Solution 2
Selenium 2 Webdriver gives us the option of the isDisplayed() method which deals with this problem. Nice work by the selenium contributors.
Solution 3
This works for me:
//div[[not(@hidden)]
David Webb
Updated on July 09, 2022Comments
-
David Webb over 1 year
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 theid
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 addingdisplay: none
to theirstyle
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 havingdisplay: none
in thestyle
.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 withdisplay: none
in thestyle
?