Search code examples
domseleniumvisible

Selenium visible element not recognized as visible


Have a look at the following code:

elem = driver.find_element_by_id(":8")
elem.click()
time.sleep(1)

elem = driver.find_element_by_id("country_residence")
print "elem visible ? = " + str(elem.value_of_css_property('visibility'))
Select(elem).select_by_value("DE")

The print states that the element is visible a this moment:

elem visible ? = visible

However, I get the following error message:

selenium.common.exceptions.ElementNotVisibleException: Message: u'Element is not currently visible and so may not be interacted with' ; Stacktrace: 
    at fxdriver.preconditions.visible (file:///var/folders/0s/j6874rlj63qccjx38ltmwy880000gn/T/tmppJ09Vu/extensions/fxdriver@googlecode.com/components/command_processor.js:8791:5)
at DelayedCommand.prototype.checkPreconditions_ (file:///var/folders/0s/j6874rlj63qccjx38ltmwy880000gn/T/tmppJ09Vu/extensions/fxdriver@googlecode.com/components/command_processor.js:11438:1)
at DelayedCommand.prototype.executeInternal_/h (file:///var/folders/0s/j6874rlj63qccjx38ltmwy880000gn/T/tmppJ09Vu/extensions/fxdriver@googlecode.com/components/command_processor.js:11455:11)
at DelayedCommand.prototype.executeInternal_ (file:///var/folders/0s/j6874rlj63qccjx38ltmwy880000gn/T/tmppJ09Vu/extensions/fxdriver@googlecode.com/components/command_processor.js:11460:7)
at DelayedCommand.prototype.execute/< (file:///var/folders/0s/j6874rlj63qccjx38ltmwy880000gn/T/tmppJ09Vu/extensions/fxdriver@googlecode.com/components/command_processor.js:11402:5) 

How is that possible?


Solution

  • The Selenium way to check whether an element is visible is to use the is_displayed() method. Given what you've described, if you do:

    elem = driver.find_element_by_id("country_residence")
    print elem.is_displayed()
    

    you should get False as a result. There are multiple reasons an element may be invisible. The visibility CSS property is one of them. There's also the display property. And then consider that the visibility of the element's parents and grandparents can affect whether it is visible. It could be off-screen, etc.

    Checking the element's visibility CSS property in isolation is definitely not the way to check whether it can be interacted with.