ElementNotVisibleException only in virtual display

2019-06-11 06:27发布

问题:

I have a script that needs to interact with a webpage via selenium. I need to use some kind of virtual display to keep the browser from showing up.

The script as a whole works great until I introduce Xvfb into the mix. When I do that I get an ElementNotVisibleException the first time I actually try to interact with the page.

I've tried using xvfbwrapper and pyvirtualdisplay with the same effect.

And here is code that doesn't work:

from xvfbwrapper import Xvfb
vdisplay = Xvfb()
vdisplay.start()
oBrowser = Browser()
oBrowser.visit(sUrl)
oBrowser.find_by_id('some_field')[0].fill(sValue)  #<--ERROR
vdisplay.stop()

And here is the code that does work (but displays the browser):

oBrowser = Browser()
oBrowser.visit(sUrl)
oBrowser.find_by_id('some_field')[0].fill(sValue) #<--works every time

So how can I run my code on a virtual display?

I've tried doing a time.sleep before trying to fill the field in but the problem doesn't seem to have anything to do with the page loading slowly. Any ideas?

回答1:

This is a workaround more than a direct solution:

I replaced this line:

oBrowser.find_by_id('some_field')[0].fill(sValue)

With this:

oBrowser.execute_script("document.getElementById('some_field').value = {}".format(sValue))

And it works reliably. I'm still not sure why it didn't just work in the first place though.