Selenium Headless Chrome: Make it Behave Like a Full Browser
In this article
To make Selenium headless Chrome behave like a full browser, you must mask the technical indicators that identify the browser as a bot. This is achieved by overriding the User-Agent string, disabling the automation flags in the browser's navigator object, setting a realistic window size, and managing cookies and headers to mimic human interaction. When Chrome runs in headless mode, it sends a specific signal to the server and the website's JavaScript that it is not a visible window, which often triggers bot detection systems, CAPTCHAs, or different page layouts. By implementing specific ChromeOptions and executing custom JavaScript, you can bypass these detection mechanisms and ensure the website renders exactly as it would for a manual user.
What You'll Need
- Python installed on your system (or Java/C# if using those bindings).
- The Selenium library installed via pip (
pip install selenium). - Google Chrome browser installed on the host machine.
- ChromeDriver that matches your current version of Google Chrome.
- A code editor or IDE (such as VS Code or PyCharm).
Step-by-Step
- Initialize ChromeOptions: Start by importing the
Optionsclass fromselenium.webdriver.chrome.options. Create an instance of this class to hold all the configurations that will modify the browser's behavior before it launches. - Enable Headless Mode: Add the headless argument to your options. Use
options.add_argument('--headless=new'). The "new" flag is critical for modern versions of Chrome, as it uses the updated headless engine that behaves much more like the headed version than the legacy headless mode did. - Set a Realistic User-Agent: By default, headless Chrome includes the word "HeadlessChrome" in its User-Agent string. Websites check this string immediately to identify bots. You must replace it with a current, real-world string. Use
options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'). Ensure the version number in the string roughly matches the version of Chrome you have installed. - Disable the Automation Flag: Chrome adds a property called
navigator.webdriverto the browser window, which is set totruewhen controlled by Selenium. Most bot detectors check this first. To hide this, useoptions.add_experimental_option("excludeSwitches", ["enable-automation"])andoptions.add_experimental_option('useAutomationExtension', False). - Define a Fixed Window Size: Headless browsers often default to a very small or non-standard resolution (like 800x600), which is a red flag for servers. Set a standard desktop resolution to ensure elements are rendered in their desktop positions. Use
options.add_argument('--window-size=1920,1080'). This prevents elements from hiding behind mobile menus or triggering responsive design shifts that might break your selectors. - Disable GPU Acceleration: In many server environments (like Linux VPS), there is no physical GPU. This can cause the browser to crash or behave inconsistently. Add
options.add_argument('--disable-gpu')to ensure stability across different hardware environments. - Implement Stealth JavaScript: Even with the flags above, some advanced scripts can still detect the automation. After the driver starts, use
driver.execute_cdp_cmdto modify the browser's internal properties. Specifically, you can use the Chrome DevTools Protocol to remove thewebdriverproperty entirely from the navigator object:driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'}). - Manage Cookies and Sessions: To further mimic a human, avoid starting every session with a completely blank slate. If possible, load a user profile directory using
options.add_argument('user-data-dir=/path/to/your/profile'). This allows the browser to retain cookies and cache, making the traffic look like a returning visitor rather than a fresh bot instance. - Introduce Random Delays: Humans do not click buttons in 0.1 seconds. Use the
time.sleep()function or, better yet, therandomlibrary to introduce variable pauses between actions. For example,time.sleep(random.uniform(1.5, 4.0))creates a more natural interaction pattern.
Common Mistakes
One of the most frequent errors is using the legacy --headless flag instead of --headless=new. The old version of headless Chrome had a completely different rendering engine that lacked support for many modern CSS and JS features, making it trivial for websites to detect. Always ensure you are using the new headless mode for maximum compatibility.
Another common mistake is forgetting to update the User-Agent string. Many developers copy a code snippet from a tutorial written three years ago and use a User-Agent from Chrome version 80 while running Chrome version 120. This mismatch (a modern browser engine reporting an ancient version) is a high-signal indicator for anti-bot software.
Developers also often overlook the navigator.webdriver property. Simply adding the --headless flag does not remove this property. If you do not explicitly disable the automation extension and use CDP commands to override the property, the website can see that the browser is being controlled by an automated tool with a single line of JavaScript.
Finally, ignoring the window size is a critical error. If you do not set a specific window size, the browser may default to a size that triggers the mobile version of a website. If your Selenium script is looking for a desktop-only ID or class, the script will fail with a NoSuchElementException, not because the element is gone, but because the layout has changed to the mobile view.
Tips
To maximize stealth, consider using a library like selenium-stealth. This is a wrapper that automatically applies many of the CDP commands and argument changes mentioned above, reducing the amount of boilerplate code you have to write and ensuring that the most current detection bypasses are applied.
When debugging a headless browser, the biggest challenge is not seeing what is happening. Use the driver.save_screenshot('debug.png') method frequently during development. By taking screenshots of the page at each critical step, you can see if a CAPTCHA has appeared, if a popup is blocking your click, or if the page has failed to load entirely.
Avoid using ImplicitlyWait for everything. While convenient, it can mask performance issues and make your scripts slower. Instead, use WebDriverWait combined with expected_conditions. This allows the browser to proceed the moment an element is available, which is more efficient and mimics the way a human waits for a page to load before interacting.
If you are scraping a site with very high security, try rotating your User-Agent strings. Instead of using one static string, maintain a list of 5-10 current Chrome User-Agents and pick one at random for each new session. This prevents the server from seeing thousands of requests from the exact same browser version and OS combination.
Troubleshooting
If you are still being detected as a bot (e.g., seeing a 403 Forbidden error or an endless loop of CAPTCHAs), first check your IP reputation. No amount of browser masking will help if your IP address belongs to a known data center range. Try running the script from a residential connection to see if the issue is the browser or the network.
If the browser crashes immediately upon launch in a Linux environment, ensure you have added the --no-sandbox and --disable-dev-shm-usage arguments. The sandbox is a security feature that often conflicts with Docker containers or restricted VPS environments, and the shared memory usage flag prevents the browser from crashing when the /dev/shm partition is too small.
When elements are not being found despite the page appearing to load, check the page source using driver.page_source. Sometimes, headless browsers are served a "challenge page" (like Cloudflare's waiting room) that doesn't render visually in a screenshot but contains a different HTML structure than the actual target page.
If you encounter SessionNotCreatedException, it almost always means your ChromeDriver version is out of sync with your Chrome browser version. Update Chrome to the latest version and then download the matching ChromeDriver, or use a manager like webdriver-manager to handle the updates automatically.
Frequently Asked Questions
Does headless mode use less RAM?
Yes, headless mode consumes significantly less memory and CPU because it does not have to render the actual graphical user interface (GUI) on your screen. This makes it ideal for running scripts on servers.
Can I still take screenshots in headless mode?
Yes, the save_screenshot method works perfectly in headless mode. The browser still renders the page internally in a virtual buffer, allowing you to capture the visual state of the page.
Will this method bypass all CAPTCHAs?
No. This method makes the browser look human, which reduces the likelihood of a CAPTCHA appearing. However, if a CAPTCHA is triggered by your IP address or behavior, these settings alone will not solve it.
Is headless Chrome slower than headed Chrome?
Generally, headless Chrome is faster because it skips the overhead of drawing the window and rendering the UI. However, the actual network request and JavaScript execution times remain the same.
Do I need a different driver for headless mode?
No, you use the same ChromeDriver regardless of whether you are running in headed or headless mode. The difference is entirely handled by the ChromeOptions you pass to the driver during initialization.
Does the --headless=new flag work on all versions?
The --headless=new flag was introduced in Chrome 109. If you are using a version older than that, you must use the legacy --headless flag, though it is highly recommended to update for better stealth.