2

I'm using the splinter module on python. I need to check if an element is visible or not on a page and seemingly the only way of telling is style="display: none;" which I can't find a way to detect.

How do check this?

1 Answers1

2

If you need to check that an element is visible or not, use the .visible attribute:

browser.find_by_css('h1').first.visible

Note that .visible is based on the is_displayed() python-selenium method which is based on this WebDriver specification which "naturally" handles the style="display: none;" case among others.


If you though, for some reason need to use the style value to locate the element, you can, of course, do so by using a CSS selector:

browser.find_by_css('[style="display: none;"]')

But this is generally fragile and you should look for other ways to locate this element.

Remember that you can also always locate multiple elements and then filter the invisible elements only, for instance:

for h1 in browser.find_by_css('h1'):
    if not h1.visible:
        # found an invisible h1 here
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Note that `find_by_css('[style="display: none;"]')` will only find elements with that exact style, while elements can inherit being hidden by ancestors, or such CSS can be just a part of the `style` tag. If not taking the `.visible` route, the next best thing would probably be the XPath inspired by [this](https://stackoverflow.com/a/651801/240443), `browser.find_by_xpath('//div[not(contains(@style,'display: none'))]//*')` – Amadan Dec 18 '17 at 04:35
  • @Amadan yeah, a string match is really-really fragile here. Even a substring check can easily be broken - e.g. no space after the `display:` and before the `none`. Thanks for the note! – alecxe Dec 18 '17 at 04:36