Can Selenium Webdriver open browser windows silently in background?

Go To StackoverFlow.com

114

I have a selenium test suite that runs many tests and on each new test it opens a browser window on top of any other windows I have open. Very jarring while working in a local environment. Any way to tell selenium or the OS (MAC) to open the windows in the background?

2013-04-23 22:46
by kevzettler
If you are doing driver = webdriver.Firefox() in your code, follow my answer here: http://stackoverflow.com/a/23898148/151581 - Stéphane Bruckert 2015-02-01 18:55


52

There are a few ways, but it isn't a simple "set a configuration value". Unless you invest in a headless browser, which doesn't suit everyone's requirements, it is a little bit of a hack:

How to hide Firefox window (Selenium WebDriver)?

and

Is it possible to hide the browser in Selenium RC?

You can 'supposedly', pass in some parameters into Chrome, specifically: --no-startup-window

Note that for some browsers, especially IE, it will hurt your tests to not have it run in focus.

You can also hack about a bit with AutoIT, to hide the window once it's opened.

2013-04-24 15:28
by Arran
"--no-startup-window" is now deprecate - Corey Goldberg 2017-11-10 04:16


132

If you are using Selenium web driver with Python,you can use PyVirtualDisplay, a Python wrapper for Xvfb and Xephyr.

PyVirtualDisplay needs Xvfb as a dependency. On Ubuntu, first install Xvfb:

sudo apt-get install xvfb

then install PyVirtualDisplay from Pypi:

pip install pyvirtualdisplay

Sample Selenium script in Python in a headless mode with PyVirtualDisplay:

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

EDIT The initial answer was posted in 2014 and now we are at the cusp of 2018.Like everything else, browsers have also advanced. Chrome has a completely headless version now which eliminates the need to use any third party libraries to hide the UI window. Sample code is as follows:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

CHROME_PATH = '/usr/bin/google-chrome'
CHROMEDRIVER_PATH = '/usr/bin/chromedriver'
WINDOW_SIZE = "1920,1080"

chrome_options = Options()  
chrome_options.add_argument("--headless")  
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH

driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
                          chrome_options=chrome_options
                         )  
driver.get("https://www.google.com")
driver.get_screenshot_as_file("capture.png")
driver.close()
2014-05-03 17:09
by Amistad
A beautiful, clean solution. Thanks for that. Works like a charm. Deserved more +1 - Eldamir 2014-05-27 07:42
Is it available for Mac OSX - vanguard69 2015-07-19 12:44
This is great if you're using Ubuntu and your test suite is in Pytho - kevzettler 2016-02-10 23:08
Does it work in windows - kame 2016-07-25 11:45
See this.http://stackoverflow.com/questions/944086/is-there-anything-like-xvfb-or-xnest-for-window - Amistad 2016-07-26 12:21
Is this possible in Java - Ali Hesari 2017-04-28 13:22
The only python specific library for this setup to work is PyvirtualDisplay..if you can find some alternative for that in Java, this will work. - Amistad 2017-04-29 14:54


27

Chrome 57 has an option to pass the --headless flag, which makes the window invisible.

This flag is different from the --no-startup-window as the last doesn't launch a window. It is used for hosting background apps, as this page says.

Java code to pass the flag to Selenium webdriver (ChromeDriver):

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
ChromeDriver chromeDriver = new ChromeDriver(options);
2017-04-21 13:25
by Marlies
Do you know if it is possible to do the same in VBA language - Martin 2017-08-01 08:52
@Martin I don't know whether your problem already has been fixed or not, but after a quick search I found those: https://github.com/prajaktamoghe/selenium-vba/issues/33 https://stackoverflow.com/questions/45121955/how-can-i-use-chrome-options-in-vba-with-selenium Does this help you - Marlies 2017-08-23 14:36
works flawlessl - bluelurker 2019-02-08 10:59


11

Since Chrome 57 you have the headless argument:

var options = new ChromeOptions();
options.AddArguments("headless");
using (IWebDriver driver = new ChromeDriver(options))
{
    // the rest of your test
}

The headless mode of Chrome performs 30.97% better than the UI version. The other headless driver PhantomJS delivers 34.92% better than the Chrome's headless mode.

PhantomJSDriver

using (IWebDriver driver = new PhantomJSDriver())
{
     // the rest of your test
}

The headless mode of Mozilla Firefox performs 3.68% better than the UI version. This is a disappointment since the Chrome's headless mode achieves > 30% better time than the UI one. The other headless driver PhantomJS delivers 34.92% better than the Chrome's headless mode. Surprisingly for me, the Edge browser beats all of them.

var options = new FirefoxOptions();
options.AddArguments("--headless");
{
    // the rest of your test
}

This is available from Firefox 57+

The headless mode of Mozilla Firefox performs 3.68% better than the UI version. This is a disappointment since the Chrome's headless mode achieves > 30% better time than the UI one. The other headless driver PhantomJS delivers 34.92% better than the Chrome's headless mode. Surprisingly for me, the Edge browser beats all of them.

Note: PhantomJS is not maintained any more!

2018-04-03 12:55
by Anton Angelov


8

I suggest using Phantom Js for more info you need to visit Phantom Official Website

As far as i know PhantomJS work only with Firefox ..

after downloading PhantomJs.exe you need to import to your project as you can see in the picture below Phantomjs is inside common>>Library>>phantomjs.exe enter image description here

Now all You have to inside your Selenium code is to change the line

browser = webdriver.Firefox()

To something like

import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)

The path to phantomjs may be different... change as you like :)

That's it, it worked for me. and definitely he will work for you to, Cheers

2016-05-29 15:16
by Ayoub
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page change - slfan 2016-05-29 15:39


7

For running without any browser, you can run it in headless mode.

I show you one example in Python that is working for me right now

from selenium import webdriver


options = webdriver.ChromeOptions()
options.add_argument("headless")
self.driver = webdriver.Chrome(executable_path='/Users/${userName}/Drivers/chromedriver', chrome_options=options)

I also add you a bit more of info about this in the official Google website https://developers.google.com/web/updates/2017/04/headless-chrome

2018-02-13 20:36
by Gonzalo Sanchez cano
Simplest answer of all - MarcioPorto 2018-05-22 22:56


4

On windows you can use win32gui:

import win32gui
import subprocess

class HideFox:
    def __init__(self, exe='firefox.exe'):
        self.exe = exe
        self.get_hwnd()


    def get_hwnd(self):
      win_name = get_win_name(self.exe)
      self.hwnd = win32gui.FindWindow(0,win_name)


    def hide(self):
        win32gui.ShowWindow(self.hwnd, 6)
        win32gui.ShowWindow(self.hwnd, 0)

    def show(self):
        win32gui.ShowWindow(self.hwnd, 5)
        win32gui.ShowWindow(self.hwnd, 3)

def get_win_name(exe):
    '''simple function that gets the window name of the process with the given name'''
    info = subprocess.STARTUPINFO()
    info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    raw=subprocess.check_output('tasklist /v /fo csv', startupinfo=info).split('\n')[1:-1]
    for proc in raw:
        try:
            proc=eval('['+proc+']')
            if proc[0]==exe:
                return proc[8]             
        except:
            pass
    raise ValueError('Could not find a process with name '+exe)

Example:

hider=HideFox('firefox.exe')  #can be anything, eq: phantomjs.exe, notepad.exe ...
#To hide the window
hider.hide()
#To show again
hider.show()

However there is one problem with this solution - using send_keys method makes the window show up. You can deal with it by using javascript which does not show window:

def send_keys_without_opening_window(id_of_the_element, keys)
    YourWebdriver.execute_script("document.getElementById('" +id_of_the_element+"').value = '"+keys+"';")
2013-10-01 20:18
by Piotr Dabkowski


0

On *nix, you can also run a headless X-server like Xvfb and point the DISPLAY variable to it:

Fake X server for testing?

2013-11-18 14:25
by user2645074


0

Here is a .net solution that worked for me:

Download PhantomJs here http://phantomjs.org/download.html

Copy the .exe from the bin folder in the download and paste in the bin debug/release folder of your Visual Studio project.

Add this using

using OpenQA.Selenium.PhantomJS;

In your code open the driver like this:

PhantomJSDriver driver = new PhantomJSDriver();
using (driver)
{
   driver.Navigate().GoToUrl("http://testing-ground.scraping.pro/login");
   //your code here 
}
2017-01-20 17:41
by Jack Fairfield


0

It may be in options. Here is the identical java code.

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setHeadless(true);
        WebDriver driver = new ChromeDriver(chromeOptions);
2019-02-07 06:25
by rinjan
Ads