User Agents

Web browsers and everyday web tech, explained

Run Selenium Chrome in Background with Python

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Running a Selenium Chrome instance in the background with Python lets your automation scripts execute without a visible browser window, freeing up your screen and allowing the script to run on servers, in CI/CD pipelines, or alongside other tasks. This guide covers the two main approaches: using the --headless flag (Chrome's built-in headless mode) and using xvfb on Linux for a virtual display. The headless method is simpler and works on all major OSes; xvfb is useful if you need to emulate a full display for certain sites. You'll need Python installed, the selenium package, and a Chrome browser (or Chromium).

What You'll Need

  • Python 3.6+ installed on your system
  • The Selenium package: pip install selenium
  • Chrome or Chromium browser installed (the latest version is recommended)
  • ChromeDriver – either download it manually or install via webdriver-manager for automatic management
  • For the xvfb method on Linux: sudo apt install xvfb (Debian/Ubuntu) or equivalent

Step-by-Step

  1. Install Selenium and WebDriver Manager (optional but recommended)
    Open a terminal and run: pip install selenium webdriver-manager. The webdriver-manager package automatically downloads and manages the correct ChromeDriver version, saving you manual setup.
  2. Import required modules
    In your Python script, import: from selenium import webdriver and from selenium.webdriver.chrome.options import Options. If using webdriver-manager, also import from webdriver_manager.chrome import ChromeDriverManager.
  3. Set up Chrome options for headless mode
    Create an Options object and add the argument --headless. You can also add --no-sandbox (often needed on Linux servers) and --disable-dev-shm-usage (to avoid shared memory issues in containers). Example:
    opts = Options()
    opts.add_argument('--headless')
    opts.add_argument('--no-sandbox')
    opts.add_argument('--disable-dev-shm-usage')
  4. Initialize the WebDriver
    Use the options to create a driver instance. With webdriver-manager: driver = webdriver.Chrome(ChromeDriverManager().install(), options=opts). Without it, you'll need to specify the path to chromedriver: driver = webdriver.Chrome(executable_path='/path/to/chromedriver', options=opts).
  5. Run your automation logic
    Write your script as usual – navigate to URLs, interact with elements, extract data, etc. The browser runs invisibly, but all operations work the same as with a visible window.
  6. Quit the driver
    Always call driver.quit() at the end of your script to close the browser and free system resources. Use a try/finally block to ensure it runs even if an error occurs.
  7. For Linux servers: use xvfb (alternative to headless)
    If headless mode causes issues with certain sites, install xvfb and run your script under a virtual display. In the terminal, run: xvfb-run python your_script.py. This creates a virtual X server, so Chrome thinks it has a display. You can also use pyvirtualdisplay in Python for more control.

Common Mistakes

  • Forgetting to add --headless – The browser will open visibly, defeating the purpose.
  • Not using driver.quit() – This leaves zombie Chrome processes that consume memory and may cause errors on subsequent runs.
  • Using an outdated ChromeDriver – Chrome updates frequently, and a mismatched driver causes a SessionNotCreatedException.
  • Running as root without --no-sandbox – On Linux, Chrome fails to start as root unless this flag is added.
  • Ignoring the --disable-dev-shm-usage flag in Docker – Without it, Chrome may crash due to limited /dev/shm size.

Tips

  • Use explicit waits – Instead of time.sleep(), use WebDriverWait to wait for elements to be present, which is more reliable and faster.
  • Set a custom user-agent – Some sites block headless browsers. You can override the user-agent via opts.add_argument('--user-agent=YOUR_UA').
  • Take screenshots for debugging – Even in headless mode, you can call driver.save_screenshot('screen.png') to see what the page looks like at a given moment.
  • Run in a virtual environment – Use python -m venv venv to isolate dependencies and avoid conflicts.
  • For long-running tasks, consider using --disable-gpu – This can reduce resource usage, though it's not always necessary.

Troubleshooting

  • ChromeDriver executable needs to be in PATH – If you get a WebDriverException about the executable, either add it to PATH or specify the full path in the executable_path argument.
  • SessionNotCreatedException – This usually means the ChromeDriver version doesn't match your Chrome version. Update ChromeDriver via webdriver-manager or download the correct one from the Chrome for Testing site.
  • Blank page or no elements found – The site might be detecting headless mode. Try adding a real user-agent and disabling automation flags: opts.add_experimental_option('excludeSwitches', ['enable-automation']).
  • Chrome crashes on startup – On Linux, ensure you have all dependencies: sudo apt install -y libxss1 libappindicator1 libindicator7 (for older versions). Also try adding --no-sandbox and --disable-dev-shm-usage.
  • Script hangs or times out – Increase the page load timeout: driver.set_page_load_timeout(30). Also check if the site uses infinite scroll or heavy JavaScript; use explicit waits instead of fixed sleeps.
  • Port already in use – If you get a Address already in use error, kill lingering Chrome processes: pkill -f chrome (Linux/macOS) or taskkill /F /IM chrome.exe (Windows).

Frequently Asked Questions

Can I run headless Chrome on Windows or macOS?

Yes, the --headless flag works on all major operating systems. No additional software is needed.

What is the difference between headless and xvfb?

Headless mode runs Chrome without any display at all, while xvfb creates a virtual display that Chrome thinks is real. Some sites behave differently in headless mode; xvfb can be a workaround if you encounter issues.

How do I pass arguments like a proxy or a specific window size?

Add them as arguments to the options object, e.g., opts.add_argument('--window-size=1920,1080') or opts.add_argument('--proxy-server=http://proxy:port').

Can I run multiple headless instances in parallel?

Yes, you can create multiple driver instances, but be mindful of resource usage. You may need to add unique user-data-dir arguments to avoid profile conflicts.

Is it possible to run headless Chrome without installing ChromeDriver separately?

Yes, using the webdriver-manager package, which downloads and manages the driver automatically. Alternatively, Selenium 4.6+ includes Selenium Manager that handles this for you.

How do I stop the script if it gets stuck?

Set a page load timeout and use explicit waits with a timeout. You can also use a watchdog timer in your script to force quit after a certain duration.