Using --disable-gpu in Pytest with Selenium
Useful to prevent Crashes in Some Environment
When running Selenium tests in headless mode with Pytest, adding the --disable-gpu flag to your Chrome options can improve stability and avoid rendering issues. This option is especially useful when executing tests on virtual machines or CI pipelines that lack dedicated GPU hardware.
Why Use --disable-gpu?
- Prevents crashes in some environments when using headless mode
- Avoids rendering issues caused by GPU acceleration in headless Chrome
- Improves compatibility with CI servers like Jenkins, GitHub Actions, or GitLab
Basic Configuration Example
Here is how to configure the Chrome driver with both --headless and --disable-gpu flags:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def test_headless_chrome():
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=options)
driver.get("https://example.com")
assert "Example Domain" in driver.title
driver.quit()
When to Use It
Use --disable-gpu when running tests in:
- Docker containers
- Linux-based headless environments
- CI/CD systems that lack a GPU
Although modern Chrome versions may not strictly require --disable-gpu when using --headless, including it remains a reliable safeguard across various platforms and test configurations.