Search code examples
pythonubuntuseleniumheadless

Selelum Headless in Ubuntu Server, minor error "The browser seems to have exited before we could connect"


So I am running Selenium on a Ubuntu Server VM and have a minor issue. When I start-up my VM and run a Selenium test script I get this error: selenium.common.exceptions.WebDriverException: Message: 'The browser seems to have exited before we could connect'. Now if I execute this export DISPLAY=:99 in the terminal before I run any of my Selenium test scripts all works fine. All tests run great headlessly!

My questions is do any of you know how to execute this command on start-up. So I don't have to run this in the terminal before I run my Selenium test scripts. I've tried adding it to the /etc/rc.local file. But this doesn't seem to work.

I've also tried executing it at the beginning of my Selenium test scripts. By just adding this (I'm using python)

os.system("export DISPLAY=:99")

Any suggestions as to how to accomplish this? Thanks in advance


Solution

  • This isn't going to work:

    os.system("export DISPLAY=:99")
    

    Because system() starts a new shell and the shell will close when finished, this influences the environment of exactly one process that is very short lived. (Child processes cannot influence the environments of their parents. Parents can only influence the environment of their children, if they make the change before executing the child process.)

    You can pick a few different mechanisms for setting the DISPLAY:

    • Set it in the scripts that start your testing mechanism

      This is especially nice if the system might do other tasks, as this will influence as little as possible. In Python, that would look like:

      os.environ["DISPLAY"]=":99"
      

      In bash(1), that would look like:

      export DISPLAY=:99
      
    • Set it in the login scripts of the user account that runs the tests.

      This is nice if the user account that runs the tests will never need a DISPLAY variable. (Though if a user logs in via ssh -X testinguser@machine ... this will clobber the usual ssh(1) X session forwarding.)

      Add this to your user's ~/.bashrc or ~/.profile or ~/.bash_profile. (See bash(1) for the differences between the files.)

      export DISPLAY=:99
      
    • Set it at login for all users. This is nice if multiple user accounts on the system will be running the testing scripts and you just want it to work for all of them. You don't care about users ever having a DISPLAY for X forwarding.

      Edit /etc/environment to add the new variable. The pam_env(8) PAM module will set the environment variables for all user accounts that authenticate under whichever services are configured to use pam_env(8) in the /etc/pam.d/ configuration directory. (This sounds more complicated than it is -- some services want authenticated users to have environment variables set, some services don't.)