How can you configure Selenium headless Chrome to run in Python?
Using ChromeOptions:
You can configure Selenium to run headless Chrome in Python by using the ChromeOptions class to set the --headless argument. Here’s an example:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# Set Chrome options
chrome_options = Options()
chrome_options.add_argument('--headless')
# Initialize the WebDriver
driver = webdriver.Chrome(options=chrome_options)
# Use the WebDriver
driver.get('https://www.example.com')
To learn how to perform headless browser testing follow this guide :
Using headless argument directly: Alternatively, you can pass the --headless argument directly when initializing the Chrome WebDriver:
from selenium import webdriver
# Set Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
# Initialize the WebDriver
driver = webdriver.Chrome(options=chrome_options)
# Use the WebDriver
driver.get('https://www.example.com')
Using headless mode with specific window size:
You can also specify a window size when running headless Chrome to simulate a specific screen resolution. Here’s an example:
from selenium import webdriver
# Set Chrome options with headless mode and window size
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--window-size=1920x1080')
# Initialize the WebDriver
driver = webdriver.Chrome(options=chrome_options)
# Use the WebDriver
driver.get('https://www.example.com')
Running headless Chrome with Selenium in Python allows you to perform automated browser testing without a visible browser window, which can be useful for running tests in headless environments or for improving test performance.