Undetected ChromeDriver in Python for Web Scraping
Have you ever tried scraping a website with Selenium, only to get blocked immediately? You see messages like “Access Denied” or endless CAPTCHA challenges. This happens because websites detect you’re using automated tools.
Undetected ChromeDriver is a modified version of Selenium ChromeDriver that helps bypass anti-bot detection systems when web scraping. It’s like wearing an invisibility cloak that makes your automated browser look exactly like a real human user.
Regular Selenium ChromeDriver leaves behind many fingerprints that websites use to detect bots. These include the navigator.webdriver property, missing Chrome extensions, unusual browser behavior, and automated user agent strings. Modern websites use sophisticated detection methods that catch standard Selenium instantly.
Undetected ChromeDriver solves this problem by patching these detection points. It removes bot signatures, mimics real browser behavior, and passes most anti-bot checks. This makes it possible to scrape websites that normally block automated access.
This guide will teach you everything about undetected-chromedriver – how it works, how to install it, and how to use it effectively for web scraping projects.
What is Undetected ChromeDriver?
Undetected ChromeDriver is a Python library that patches Selenium ChromeDriver to avoid detection by anti-bot systems. Think of it as an upgraded version of Selenium that knows how to hide its automation fingerprints.
Regular Selenium ChromeDriver was designed for testing web applications, not for scraping. When you use it, the browser includes several properties that scream “I’m a bot!” Websites check for these properties and block automated access.
The main detection point is the navigator.webdriver property. In normal Chrome, this property is undefined. In Selenium, it’s set to true. Websites simply check this property with JavaScript – if it’s true, you’re blocked.
Undetected ChromeDriver patches this and many other detection points. It modifies ChromeDriver at runtime to remove these bot signatures. The result is a browser that looks and behaves like a real human is controlling it.
The library was created by ultrafunkamsterdam and is actively maintained on GitHub. It’s built on top of Selenium, so you use the same familiar Selenium commands. The difference is under the hood – all the anti-detection patches happen automatically.
Key features include:
- Automatic ChromeDriver version management
- Removes
navigator.webdriverflag - Patches Chrome DevTools Protocol detection
- Handles common anti-bot systems like Cloudflare
- Works with most Selenium commands
- Supports headless mode with anti-detection
The library is particularly useful for scraping websites protected by Cloudflare, DataDome, PerimeterX, and other bot detection services.
How Bot Detection Works
Websites detect bots by checking browser properties, analyzing behavior patterns, and using fingerprinting techniques. Understanding how detection works helps you appreciate why undetected-chromedriver is necessary.
Browser Property Checks
The simplest detection method checks specific JavaScript properties. The most common check is:
if (navigator.webdriver) {
// This is a bot, block it
}
Regular Selenium sets navigator.webdriver to true, making detection instant. Other properties websites check include:
window.chrome– Should exist in real Chromenavigator.plugins– Should contain browser pluginsnavigator.languages– Should match browser settingsnavigator.permissions– Real browsers have permission APIs
Chrome DevTools Protocol
Selenium communicates with Chrome through the Chrome DevTools Protocol (CDP). Websites can detect this communication by:
- Checking for CDP runtime flags
- Looking for automation extension artifacts
- Detecting specific CDP command signatures
Undetected ChromeDriver patches these CDP-related detection points.
Browser Fingerprinting
Advanced detection systems create unique fingerprints based on:
- Screen resolution and color depth
- Installed fonts and their rendering
- Canvas and WebGL rendering signatures
- Audio context fingerprints
- Battery API and hardware data
- Timezone and language settings
Each combination creates a unique fingerprint. Headless browsers often have fingerprints that don’t match real devices, making them easy to detect.
Behavioral Analysis
Sophisticated systems analyze how you interact with the page:
- Mouse movement patterns (bots move in straight lines)
- Click timing and precision
- Scroll behavior (bots scroll unnaturally)
- Keyboard input timing
- Touch event patterns on mobile
Real humans have imperfect, variable behavior. Bots are too perfect and consistent.
Network Analysis
Some detection systems analyze network-level indicators:
- Request timing patterns
- Missing common browser requests (images, CSS, fonts)
- HTTP header inconsistencies
- TLS fingerprints that don’t match the claimed browser
- WebRTC IP leaks showing data center origins
CAPTCHA Challenges
When detection systems suspect a bot but aren’t certain, they show CAPTCHA challenges. Common types include:
- reCAPTCHA – Google’s CAPTCHA system
- hCaptcha – Privacy-focused alternative
- Cloudflare Turnstile – Cloudflare’s CAPTCHA
- Image recognition challenges
- Puzzle challenges
These force you to prove you’re human, stopping automated scrapers.
Common Anti-Bot Solutions
Popular commercial anti-bot solutions include:
- Cloudflare Bot Management – Protects millions of websites
- DataDome – Real-time bot detection
- PerimeterX – Behavioral analysis
- Akamai Bot Manager – Enterprise protection
- AWS WAF – Amazon’s web application firewall
Each uses different combinations of the detection methods above. Undetected ChromeDriver helps bypass many of these systems.
Installing Undetected ChromeDriver
Installing undetected-chromedriver is simple using pip, Python’s package manager. Here’s the complete installation process.
Prerequisites
Before installing, make sure you have:
- Python 3.7 or higher installed
- pip package manager (comes with Python)
- Google Chrome browser installed on your system
Check your Python version:
python --version
Basic Installation
Install undetected-chromedriver using pip:
pip install undetected-chromedriver
This installs the latest version. The library automatically downloads the correct ChromeDriver version to match your installed Chrome browser.
Installing Specific Versions
To install a specific version:
pip install undetected-chromedriver==3.5.4
Upgrading Existing Installation
If you already have it installed and want to upgrade:
pip install --upgrade undetected-chromedriver
Installing with Requirements File
For project dependency management, add to your requirements.txt:
undetected-chromedriver>=3.5.0
Then install:
pip install -r requirements.txt
Verifying Installation
Test your installation with a simple script:
import undetected_chromedriver as uc
driver = uc.Chrome()
driver.get('https://www.google.com')
print(driver.title)
driver.quit()
If this runs without errors and opens a Chrome window, your installation is successful.
Common Installation Issues
Issue: Chrome binary not found
Solution: Make sure Chrome is installed at the default location. Or specify the path manually:
import undetected_chromedriver as uc options = uc.ChromeOptions() options.binary_location = '/path/to/chrome' driver = uc.Chrome(options=options)
Issue: Version mismatch errors
Solution: Let undetected-chromedriver auto-download the correct version:
import undetected_chromedriver as uc driver = uc.Chrome(version_main=None) # Auto-detect Chrome version
Issue: Permission errors
Solution: Run with appropriate permissions or install in a virtual environment:
python -m venv myenv source myenv/bin/activate # On Windows: myenv\Scripts\activate pip install undetected-chromedriver
Dependencies
Undetected-chromedriver automatically installs these dependencies:
- selenium – Web browser automation
- requests – HTTP library
- websockets – WebSocket client
These are handled automatically during installation.
Basic Usage of Undetected ChromeDriver
Using undetected-chromedriver is very similar to using regular Selenium, with just a few differences in initialization. Here’s how to get started.
Simple Example
The most basic usage:
import undetected_chromedriver as uc
# Create driver instance
driver = uc.Chrome()
# Navigate to a website
driver.get('https://dataprixa.com')
# Get page title
print(driver.title)
# Close browser
driver.quit()
This creates an undetected Chrome browser, visits a website, prints the title, and closes the browser.
Finding Elements
Use standard Selenium methods to find elements:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
driver = uc.Chrome()
driver.get('https://dataprixa.com')
# Find element by ID
element = driver.find_element(By.ID, 'element-id')
# Find element by class name
element = driver.find_element(By.CLASS_NAME, 'my-class')
# Find element by CSS selector
element = driver.find_element(By.CSS_SELECTOR, 'div.container > p')
# Find element by XPath
element = driver.find_element(By.XPATH, '//div[@class="content"]/p')
# Find multiple elements
elements = driver.find_elements(By.TAG_NAME, 'a')
driver.quit()
Interacting with Elements
Click, type, and interact just like regular Selenium:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
driver = uc.Chrome()
driver.get('https://www.google.com')
# Find search box
search_box = driver.find_element(By.NAME, 'q')
# Type into search box
search_box.send_keys('web scraping')
# Press Enter
search_box.send_keys(Keys.RETURN)
# Wait for results to load
time.sleep(2)
# Get page source
html = driver.page_source
print(html[:500]) # Print first 500 characters
driver.quit()
Getting Page Content
Extract text and HTML content:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
driver = uc.Chrome()
driver.get('https://dataprixa.com')
# Get page source (full HTML)
html = driver.page_source
# Get text from specific element
element = driver.find_element(By.TAG_NAME, 'h1')
text = element.text
print(f"Heading: {text}")
# Get attribute value
link = driver.find_element(By.TAG_NAME, 'a')
href = link.get_attribute('href')
print(f"Link URL: {href}")
driver.quit()
Taking Screenshots
Capture screenshots for debugging:
import undetected_chromedriver as uc
driver = uc.Chrome()
driver.get('https://dataprixa.com')
# Take screenshot of entire page
driver.save_screenshot('screenshot.png')
# Or get screenshot as bytes
screenshot_bytes = driver.get_screenshot_as_png()
driver.quit()
Executing JavaScript
Run custom JavaScript in the browser:
import undetected_chromedriver as uc
driver = uc.Chrome()
driver.get('https://dataprixa.com')
# Execute JavaScript
title = driver.execute_script('return document.title')
print(f"Title: {title}")
# Scroll to bottom of page
driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
# Modify page elements
driver.execute_script('document.querySelector("h1").style.color = "red"')
driver.quit()
Waiting for Elements
Use waits instead of sleep for better reliability:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = uc.Chrome()
driver.get('https://dataprixa.com')
# Wait up to 10 seconds for element to appear
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'my-element'))
)
print('Element found!')
except:
print('Element not found within 10 seconds')
driver.quit()
Multiple Tabs
Work with multiple browser tabs:
import undetected_chromedriver as uc
import time
driver = uc.Chrome()
# Open first page
driver.get('https://dataprixa.com')
print(f"First tab: {driver.title}")
# Open new tab
driver.execute_script("window.open('https://google.com', '_blank')")
# Switch to new tab
driver.switch_to.window(driver.window_handles[1])
time.sleep(2)
print(f"Second tab: {driver.title}")
# Switch back to first tab
driver.switch_to.window(driver.window_handles[0])
print(f"Back to first tab: {driver.title}")
driver.quit()
These basic operations work just like regular Selenium web scraping, but with anti-detection built in.
Advanced Configuration Options
Undetected ChromeDriver offers many configuration options to customize browser behavior and improve stealth. These advanced settings help bypass more sophisticated detection systems.
Headless Mode
Run Chrome without a visible window:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
options.add_argument('--headless=new') # New headless mode
# Or use: options.headless = True
driver = uc.Chrome(options=options)
driver.get('https://dataprixa.com')
print(driver.title)
driver.quit()
Note: Headless mode is easier to detect. Use it carefully and test thoroughly.
Custom User Agent
Change the browser’s user agent string:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
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'
options.add_argument(f'--user-agent={user_agent}')
driver = uc.Chrome(options=options)
driver.get('https://dataprixa.com')
driver.quit()
Window Size and Position
Control browser window dimensions:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
options.add_argument('--window-size=1920,1080')
options.add_argument('--start-maximized')
driver = uc.Chrome(options=options)
driver.get('https://dataprixa.com')
# Or set after creation
driver.set_window_size(1920, 1080)
driver.set_window_position(0, 0)
driver.quit()
Disable Images and CSS
Speed up scraping by blocking images and CSS:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
# Disable images
prefs = {
'profile.managed_default_content_settings.images': 2,
'profile.default_content_setting_values.images': 2
}
options.add_experimental_option('prefs', prefs)
driver = uc.Chrome(options=options)
driver.get('https://dataprixa.com')
driver.quit()
Using Proxies
Route traffic through proxy servers:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
# HTTP proxy
options.add_argument('--proxy-server=http://proxy-server:port')
# SOCKS5 proxy
# options.add_argument('--proxy-server=socks5://proxy-server:port')
driver = uc.Chrome(options=options)
driver.get('https://example.com')
driver.quit()
For authenticated proxies:
import undetected_chromedriver as uc options = uc.ChromeOptions() # Create proxy extension for authentication proxy = 'proxy-server:port' proxy_user = 'username' proxy_pass = 'password' # This requires creating a Chrome extension with proxy credentials # More complex setup - see proxy authentication section below driver = uc.Chrome(options=options)
Learn more about using proxies for web scraping.
Disable Automation Flags
Remove additional automation indicators:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
# Disable blink features
options.add_argument('--disable-blink-features=AutomationControlled')
# Additional flags
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')
options.add_argument('--disable-gpu')
options.add_argument('--disable-features=VizDisplayCompositor')
driver = uc.Chrome(options=options)
driver.get('https://dataprixa.com')
driver.quit()
Custom Chrome Binary
Use a specific Chrome installation:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
options.binary_location = '/path/to/chrome/binary'
driver = uc.Chrome(options=options)
driver.get('https://dataprixa.com')
driver.quit()
Browser Profile
Use an existing Chrome profile with history and cookies:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
options.add_argument('--user-data-dir=/path/to/chrome/profile')
driver = uc.Chrome(options=options)
driver.get('https://dataprixa.com')
driver.quit()
This loads your real Chrome profile with all your browsing history, cookies, and extensions.
Suppress Logging
Reduce console output:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
options.add_argument('--log-level=3') # Only show fatal errors
options.add_argument('--silent')
driver = uc.Chrome(options=options, suppress_welcome=True)
driver.get('https://dataprixa.com')
driver.quit()
Version Control
Specify ChromeDriver version:
import undetected_chromedriver as uc
# Let it auto-detect (recommended)
driver = uc.Chrome(version_main=None)
# Or specify major version
# driver = uc.Chrome(version_main=120)
driver.get('https://dataprixa.com')
driver.quit()
Enable Browser Extensions
Load Chrome extensions for additional functionality:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
options.add_argument('--load-extension=/path/to/extension')
driver = uc.Chrome(options=options)
driver.get('https://dataprixa.com')
driver.quit()
These advanced options give you fine control over browser behavior to match specific scraping requirements.
Bypassing Cloudflare Protection
Cloudflare is one of the most common anti-bot systems protecting websites. Undetected ChromeDriver can bypass many Cloudflare challenges automatically.
Understanding Cloudflare Challenges
Cloudflare uses several protection levels:
- JavaScript Challenge – Browser must execute JavaScript
- Managed Challenge – Interactive CAPTCHA
- I’m Under Attack Mode – Aggressive bot blocking
- Bot Fight Mode – Blocks suspected bots
Most of the time, you’ll encounter JavaScript challenges. These check if you’re a real browser by running JavaScript tests.
Basic Cloudflare Bypass
Simple approach for Cloudflare-protected sites:
import undetected_chromedriver as uc
import time
options = uc.ChromeOptions()
options.add_argument('--start-maximized')
driver = uc.Chrome(options=options)
# Navigate to Cloudflare-protected site
driver.get('https://cloudflare-protected-site.com')
# Wait for Cloudflare to complete check
time.sleep(5)
# Check if we passed
if 'Just a moment' in driver.page_source:
print('Still waiting for Cloudflare...')
time.sleep(5)
else:
print('Cloudflare bypass successful!')
# Now scrape the page
html = driver.page_source
print(html[:500])
driver.quit()
Handling “Checking your browser” Page
Cloudflare shows a “Checking your browser” message while running tests:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = uc.Chrome()
driver.get('https://cloudflare-protected-site.com')
try:
# Wait for Cloudflare challenge to complete
# This waits for the challenge page to disappear
WebDriverWait(driver, 10).until_not(
EC.presence_of_element_located((By.ID, 'challenge-running'))
)
print('Cloudflare challenge passed!')
except:
print('Cloudflare challenge still running...')
time.sleep(5)
# Continue scraping
html = driver.page_source
driver.quit()
Using Real Chrome Profile
Using your actual Chrome profile can help pass Cloudflare:
import undetected_chromedriver as uc
import os
# Get your Chrome profile path
# Windows: C:/Users/YourName/AppData/Local/Google/Chrome/User Data
# Mac: ~/Library/Application Support/Google/Chrome
# Linux: ~/.config/google-chrome
profile_path = os.path.expanduser('~/Library/Application Support/Google/Chrome')
options = uc.ChromeOptions()
options.add_argument(f'--user-data-dir={profile_path}')
options.add_argument('--profile-directory=Default')
driver = uc.Chrome(options=options)
driver.get('https://cloudflare-protected-site.com')
# Your real profile has cookies and browsing history
# This makes you look more like a real user
time.sleep(5)
html = driver.page_source
driver.quit()
Rotating User Agents
Change user agents to avoid fingerprinting:
import undetected_chromedriver as uc
import random
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
]
options = uc.ChromeOptions()
options.add_argument(f'--user-agent={random.choice(user_agents)}')
driver = uc.Chrome(options=options)
driver.get('https://cloudflare-protected-site.com')
time.sleep(5)
driver.quit()
Handling Turnstile CAPTCHA
Cloudflare’s Turnstile CAPTCHA sometimes appears. Here’s how to detect it:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
import time
driver = uc.Chrome()
driver.get('https://cloudflare-protected-site.com')
time.sleep(5)
# Check if Turnstile CAPTCHA appeared
try:
captcha = driver.find_element(By.CSS_SELECTOR, '[name="cf-turnstile-response"]')
print('Turnstile CAPTCHA detected!')
print('Manual solving required or use CAPTCHA solving service')
# Wait for manual solving
input('Solve the CAPTCHA manually and press Enter...')
except:
print('No CAPTCHA detected')
html = driver.page_source
driver.quit()
Learn more about Cloudflare Turnstile.
Combining with Proxies
Use proxies to avoid IP-based blocking:
import undetected_chromedriver as uc
import time
options = uc.ChromeOptions()
options.add_argument('--proxy-server=http://proxy:port')
driver = uc.Chrome(options=options)
driver.get('https://cloudflare-protected-site.com')
time.sleep(5)
if 'Just a moment' not in driver.page_source:
print('Successfully bypassed Cloudflare with proxy!')
html = driver.page_source
else:
print('Cloudflare still checking...')
driver.quit()
Best Practices for Cloudflare Bypass
- Use realistic delays – Don’t rush through pages
- Maintain sessions – Keep cookies between requests
- Rotate IPs – Use residential proxies for better success
- Mimic human behavior – Random mouse movements, scrolling
- Don’t scrape too fast – Respect rate limits
- Use real browser profiles – More authentic fingerprint
Common Cloudflare Error Codes
When scraping Cloudflare-protected sites, you might see these errors:
- Error 1020 – Access denied (IP banned)
- Error 1009 – Access denied (country/region banned)
- Error 1010 – Browser signature banned
- Error 1015 – Rate limiting
Each error requires different handling strategies.
Handling Login and Authentication
Many scraping tasks require logging into websites before accessing data. Undetected ChromeDriver handles login automation effectively.
Basic Login Example
Simple login form automation:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = uc.Chrome()
# Go to login page
driver.get('https://example.com/login')
# Find and fill username field
username_field = driver.find_element(By.ID, 'username')
username_field.send_keys('your_username')
# Find and fill password field
password_field = driver.find_element(By.ID, 'password')
password_field.send_keys('your_password')
# Click login button
login_button = driver.find_element(By.ID, 'login-button')
login_button.click()
# Wait for login to complete
time.sleep(3)
# Verify login success
if 'dashboard' in driver.current_url:
print('Login successful!')
else:
print('Login failed')
driver.quit()
Learn more about scraping websites that require login.
Saving and Loading Cookies
Save cookies to reuse sessions without logging in every time:
import undetected_chromedriver as uc
import pickle
import time
driver = uc.Chrome()
# First time: Login and save cookies
driver.get('https://example.com/login')
# Perform login...
# (login code here)
time.sleep(3)
# Save cookies to file
cookies = driver.get_cookies()
with open('cookies.pkl', 'wb') as f:
pickle.dump(cookies, f)
print('Cookies saved!')
driver.quit()
# Next time: Load cookies without logging in
driver = uc.Chrome()
driver.get('https://example.com')
# Load cookies
with open('cookies.pkl', 'rb') as f:
cookies = pickle.load(f)
for cookie in cookies:
driver.add_cookie(cookie)
# Refresh to apply cookies
driver.refresh()
time.sleep(2)
# Now you're logged in!
print('Logged in using saved cookies')
driver.quit()
Using Real Chrome Profile
Use your actual Chrome profile where you’re already logged in:
import undetected_chromedriver as uc
import os
# Your Chrome profile path
profile_path = os.path.expanduser('~/Library/Application Support/Google/Chrome')
options = uc.ChromeOptions()
options.add_argument(f'--user-data-dir={profile_path}')
options.add_argument('--profile-directory=Default')
driver = uc.Chrome(options=options)
# Navigate to site - you're already logged in
driver.get('https://example.com/dashboard')
# Continue scraping as logged-in user
driver.quit()
This is the easiest method – you’re using your real browser session where you’re already logged in.
Handling Two-Factor Authentication (2FA)
For sites with 2FA, you need to handle the extra step:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
import time
driver = uc.Chrome()
driver.get('https://example.com/login')
# Enter username and password
driver.find_element(By.ID, 'username').send_keys('your_username')
driver.find_element(By.ID, 'password').send_keys('your_password')
driver.find_element(By.ID, 'login-button').click()
time.sleep(2)
# Check if 2FA page appeared
if '2fa' in driver.current_url or 'verify' in driver.current_url:
print('2FA required')
# Option 1: Wait for manual input
print('Please enter 2FA code manually in the browser')
input('Press Enter after entering 2FA code...')
# Option 2: Automated 2FA (if you have API access)
# code = get_2fa_code() # Your function to get code
# driver.find_element(By.ID, '2fa-code').send_keys(code)
# driver.find_element(By.ID, 'verify-button').click()
time.sleep(3)
print('Login complete')
driver.quit()
OAuth and Social Login
Handle social login buttons:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
import time
driver = uc.Chrome()
driver.get('https://example.com/login')
# Click "Login with Google" button
google_login = driver.find_element(By.ID, 'google-login')
google_login.click()
# Wait for Google login page
time.sleep(2)
# Switch to Google login window if it's a popup
if len(driver.window_handles) > 1:
driver.switch_to.window(driver.window_handles[1])
# Fill Google login form
driver.find_element(By.ID, 'identifierId').send_keys('[email protected]')
driver.find_element(By.ID, 'identifierNext').click()
time.sleep(2)
driver.find_element(By.NAME, 'password').send_keys('your_password')
driver.find_element(By.ID, 'passwordNext').click()
time.sleep(3)
# Switch back to main window
if len(driver.window_handles) > 1:
driver.switch_to.window(driver.window_handles[0])
print('OAuth login complete')
driver.quit()
Maintaining Session State
Keep sessions alive across multiple page visits:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
import time
driver = uc.Chrome()
# Login once
driver.get('https://example.com/login')
driver.find_element(By.ID, 'username').send_keys('your_username')
driver.find_element(By.ID, 'password').send_keys('your_password')
driver.find_element(By.ID, 'login-button').click()
time.sleep(3)
# Now visit multiple pages while logged in
pages = [
'https://example.com/page1',
'https://example.com/page2',
'https://example.com/page3'
]
for page in pages:
driver.get(page)
time.sleep(2)
# Scrape page content
html = driver.page_source
print(f'Scraped: {page}')
# Check if still logged in
if 'login' in driver.current_url:
print('Session expired, need to login again')
break
driver.quit()
These techniques let you scrape authenticated areas of websites that require login credentials.
Scraping Dynamic Content
Many modern websites load content dynamically using JavaScript. Undetected ChromeDriver excels at scraping these dynamic websites because it renders JavaScript just like a real browser.
Waiting for JavaScript to Load
The most important skill for dynamic scraping is waiting for content to load:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = uc.Chrome()
driver.get('https://dynamic-site.com')
# Wait for specific element to appear
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, 'dynamic-content'))
)
print('Element loaded!')
print(element.text)
except:
print('Element did not load within 10 seconds')
driver.quit()
Scrolling to Load More Content
Many sites load content as you scroll (infinite scroll):
import undetected_chromedriver as uc
import time
driver = uc.Chrome()
driver.get('https://infinite-scroll-site.com')
# Scroll down multiple times
for i in range(5):
# Scroll to bottom
driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
print(f'Scrolled {i+1} times')
time.sleep(2) # Wait for content to load
# Now get all loaded content
html = driver.page_source
print(f'Total page length: {len(html)} characters')
driver.quit()
Clicking “Load More” Buttons
Some sites use buttons to load additional content:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
import time
driver = uc.Chrome()
driver.get('https://example.com/articles')
# Click "Load More" button multiple times
for i in range(5):
try:
load_more = driver.find_element(By.CLASS_NAME, 'load-more-button')
load_more.click()
print(f'Clicked Load More button {i+1} times')
time.sleep(2) # Wait for content to load
except:
print('No more Load More button found')
break
# Scrape all loaded content
articles = driver.find_elements(By.CLASS_NAME, 'article')
print(f'Found {len(articles)} articles')
driver.quit()
Handling AJAX Requests
Wait for AJAX requests to complete:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = uc.Chrome()
driver.get('https://ajax-site.com')
# Click button that triggers AJAX
button = driver.find_element(By.ID, 'load-data')
button.click()
# Wait for AJAX to complete (loading spinner disappears)
WebDriverWait(driver, 10).until(
EC.invisibility_of_element_located((By.CLASS_NAME, 'loading-spinner'))
)
# Wait for result to appear
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, 'ajax-result'))
)
# Now scrape the loaded data
result = driver.find_element(By.CLASS_NAME, 'ajax-result')
print(result.text)
driver.quit()
Scraping Single Page Applications (SPAs)
SPAs like React or Vue apps load everything via JavaScript:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = uc.Chrome()
driver.get('https://react-spa.com')
# Wait for React app to fully load
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'root'))
)
# Additional wait for content inside the app
time.sleep(3)
# Navigate within SPA (changes URL without page reload)
nav_link = driver.find_element(By.LINK_TEXT, 'Products')
nav_link.click()
# Wait for new content to load
time.sleep(2)
# Scrape SPA content
products = driver.find_elements(By.CLASS_NAME, 'product-item')
print(f'Found {products} products')
for product in products:
name = product.find_element(By.CLASS_NAME, 'product-name').text
price = product.find_element(By.CLASS_NAME, 'product-price').text
print(f'{name}: {price}')
driver.quit()
Handling Lazy-Loaded Images
Images that load only when scrolled into view:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
import time
driver = uc.Chrome()
driver.get('https://image-gallery.com')
# Scroll slowly to trigger lazy loading
scroll_pause_time = 1
last_height = driver.execute_script('return document.body.scrollHeight')
while True:
# Scroll down
driver.execute_script('window.scrollBy(0, 500)')
time.sleep(scroll_pause_time)
# Check if reached bottom
new_height = driver.execute_script('return document.body.scrollHeight')
if new_height == last_height:
break
last_height = new_height
# Now all images should be loaded
images = driver.find_elements(By.TAG_NAME, 'img')
print(f'Found {len(images)} images')
for img in images:
src = img.get_attribute('src')
print(src)
driver.quit()
Waiting for Specific Text to Appear
Wait for certain text to be present on the page:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = uc.Chrome()
driver.get('https://dynamic-site.com')
# Wait for specific text to appear
try:
WebDriverWait(driver, 10).until(
EC.text_to_be_present_in_element(
(By.CLASS_NAME, 'status'),
'Complete'
)
)
print('Status changed to Complete!')
except:
print('Text did not appear')
driver.quit()
Learn more about handling dynamic content in web scraping.
Common Issues and Solutions
Even with undetected-chromedriver, you might encounter problems. Here are common issues and how to fix them.
Issue: “Chrome failed to start”
Problem: Chrome browser won’t launch
Solutions:
import undetected_chromedriver as uc
# Solution 1: Add no-sandbox flag
options = uc.ChromeOptions()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = uc.Chrome(options=options)
Or specify Chrome binary location:
options = uc.ChromeOptions()
options.binary_location = '/usr/bin/google-chrome' # Adjust path
driver = uc.Chrome(options=options)
Issue: “Session not created: version mismatch”
Problem: ChromeDriver version doesn’t match Chrome version
Solution:
import undetected_chromedriver as uc
# Let it auto-detect and download correct version
driver = uc.Chrome(version_main=None)
Or manually specify version:
# If you have Chrome 120
driver = uc.Chrome(version_main=120)
Issue: Still Getting Detected as Bot
Problem: Website still blocks you despite using undetected-chromedriver
Solutions:
Add more stealth options:
import undetected_chromedriver as uc
import time
options = uc.ChromeOptions()
# More stealth flags
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')
options.add_argument('--disable-gpu')
# Start maximized (headless can be detected)
options.add_argument('--start-maximized')
driver = uc.Chrome(options=options)
# Add random delays
driver.get('https://example.com')
time.sleep(3) # Random human-like delay
driver.quit()
Use residential proxies:
options.add_argument('--proxy-server=http://residential-proxy:port')
Issue: Headless Mode Detected
Problem: Headless browsers are easier to detect
Solution:
Use new headless mode:
import undetected_chromedriver as uc
options = uc.ChromeOptions()
options.add_argument('--headless=new') # New headless mode
driver = uc.Chrome(options=options)
Or use virtual display (Linux):
sudo apt-get install xvfb
from xvfbwrapper import Xvfb
vdisplay = Xvfb()
vdisplay.start()
# Run Chrome normally (not headless)
driver = uc.Chrome()
# Your scraping code here
driver.quit()
vdisplay.stop()
Issue: Elements Not Found
Problem: find_element() throws NoSuchElementException
Solution:
Use proper waits:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = uc.Chrome()
driver.get('https://example.com')
try:
# Wait up to 10 seconds for element
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'my-element'))
)
element.click()
except:
print('Element not found after waiting')
driver.quit()
Issue: Timeout Errors
Problem: Operations timeout before completing
Solution:
Increase timeouts:
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = uc.Chrome()
# Set page load timeout
driver.set_page_load_timeout(30) # 30 seconds
# Set script timeout
driver.set_script_timeout(30)
# Increase wait timeout
driver.get('https://slow-site.com')
element = WebDriverWait(driver, 30).until( # Wait 30 seconds
EC.presence_of_element_located((By.ID, 'content'))
)
driver.quit()
Issue: Memory Leaks
Problem: Script uses too much memory over time
Solution:
Restart driver periodically:
import undetected_chromedriver as uc
urls = ['url1', 'url2', 'url3', ...] # Many URLs
for i, url in enumerate(urls):
# Restart driver every 50 requests
if i % 50 == 0:
if i > 0:
driver.quit()
driver = uc.Chrome()
driver.get(url)
# Scrape...
driver.quit()
Issue: CAPTCHA Challenges
Problem: Website shows CAPTCHA despite anti-detection
Solution:
Manual solving:
import undetected_chromedriver as uc
import time
driver = uc.Chrome()
driver.get('https://captcha-site.com')
# Check for CAPTCHA
if 'captcha' in driver.page_source.lower():
print('CAPTCHA detected - please solve manually')
input('Press Enter after solving CAPTCHA...')
# Continue scraping
html = driver.page_source
driver.quit()
Or use CAPTCHA solving services (paid):
# Example with 2Captcha service
# captcha_solution = solve_captcha_with_service(driver)
# driver.find_element(By.ID, 'captcha-response').send_keys(captcha_solution)
Learn more about bypassing CAPTCHA in web scraping.
Best Practices and Tips
Following best practices improves success rates and reduces detection risks. Here are proven strategies for effective scraping with undetected-chromedriver.
Add Random Delays
Mimic human behavior with random timing:
import undetected_chromedriver as uc
import time
import random
driver = uc.Chrome()
urls = ['url1', 'url2', 'url3']
for url in urls:
driver.get(url)
# Random delay between 2-5 seconds
delay = random.uniform(2, 5)
time.sleep(delay)
# Scrape page...
driver.quit()
Rotate User Agents
Change user agents between sessions:
import undetected_chromedriver as uc
import random
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
]
for i in range(5):
options = uc.ChromeOptions()
options.add_argument(f'--user-agent={random.choice(user_agents)}')
driver = uc.Chrome(options=options)
driver.get('https://example.com')
# Scrape...
driver.quit()
Handle Errors Gracefully
Implement proper error handling:
import undetected_chromedriver as uc
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import time
driver = uc.Chrome()
urls = ['url1', 'url2', 'url3']
for url in urls:
try:
driver.get(url)
time.sleep(2)
# Try to scrape
content = driver.find_element(By.CLASS_NAME, 'content').text
print(f'Scraped: {url}')
except TimeoutException:
print(f'Timeout on {url}')
continue
except NoSuchElementException:
print(f'Element not found on {url}')
continue
except Exception as e:
print(f'Error on {url}: {str(e)}')
continue
driver.quit()
Clean Up Resources
Always close drivers properly:
import undetected_chromedriver as uc
driver = None
try:
driver = uc.Chrome()
driver.get('https://example.com')
# Scraping code...
except Exception as e:
print(f'Error: {str(e)}')
finally:
if driver:
driver.quit()
Monitor Resource Usage
Track memory and performance:
import undetected_chromedriver as uc
import psutil
import time
driver = uc.Chrome()
# Get process info
process = psutil.Process()
for i in range(10):
driver.get(f'https://example.com/page{i}')
# Check memory usage
memory_mb = process.memory_info().rss / 1024 / 1024
print(f'Memory usage: {memory_mb:.2f} MB')
# Restart if memory too high
if memory_mb > 500:
print('Memory high, restarting driver...')
driver.quit()
driver = uc.Chrome()
time.sleep(2)
driver.quit()
Use Context Managers
Cleaner code with automatic cleanup:
import undetected_chromedriver as uc
from contextlib import contextmanager
@contextmanager
def get_driver():
driver = uc.Chrome()
try:
yield driver
finally:
driver.quit()
# Usage
with get_driver() as driver:
driver.get('https://example.com')
# Scraping code...
# Driver automatically closes
Log Your Activity
Track scraping progress:
import undetected_chromedriver as uc
import logging
import time
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='scraper.log'
)
driver = uc.Chrome()
urls = ['url1', 'url2', 'url3']
for url in urls:
try:
logging.info(f'Scraping {url}')
driver.get(url)
time.sleep(2)
html = driver.page_source
logging.info(f'Successfully scraped {url} - {len(html)} chars')
except Exception as e:
logging.error(f'Failed to scrape {url}: {str(e)}')
driver.quit()
logging.info('Scraping completed')
Respect Website Resources
Be a good web citizen:
- Add reasonable delays between requests (2-5 seconds minimum)
- Don’t scrape during peak hours
- Cache responses to avoid re-scraping
- Follow robots.txt guidelines
- Limit concurrent connections
- Use appropriate user agents
- Contact website owners for permission when scraping large amounts
Learn more about web scraping best practices.
Test in Development First
Always test on development environments:
import undetected_chromedriver as uc
# Development mode with visible browser
DEV_MODE = True
if DEV_MODE:
driver = uc.Chrome() # Visible browser for debugging
else:
options = uc.ChromeOptions()
options.add_argument('--headless=new')
driver = uc.Chrome(options=options)
driver.get('https://example.com')
# Test your scraping logic...
driver.quit()
Alternatives to Undetected ChromeDriver
While undetected-chromedriver is powerful, other tools exist for bypassing bot detection. Here are notable alternatives.
Playwright with Stealth
Playwright is a modern browser automation library from Microsoft:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.goto('https://example.com')
content = page.content()
print(content[:500])
browser.close()
Playwright has built-in stealth features and is harder to detect than Selenium.
Puppeteer (Node.js)
Puppeteer is a Node.js library for Chrome automation:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
const content = await page.content();
console.log(content);
await browser.close();
})();
Often used with puppeteer-extra-plugin-stealth for anti-detection.
Selenium Wire
Selenium Wire intercepts and modifies requests:
from seleniumwire import webdriver
driver = webdriver.Chrome()
driver.get('https://example.com')
# Access requests
for request in driver.requests:
if request.response:
print(request.url, request.response.status_code)
driver.quit()
Useful for analyzing and modifying network traffic.
ScraperAPI
Commercial service that handles anti-bot measures automatically:
import requests
api_key = 'your_api_key'
url = 'https://example.com'
response = requests.get(
'http://api.scraperapi.com',
params={'api_key': api_key, 'url': url}
)
print(response.text)
Handles proxies, JavaScript rendering, and CAPTCHA solving automatically.
Bright Data
Enterprise scraping infrastructure with residential proxies and browser unblocking.
Selenium with Stealth Plugin
Add stealth to regular Selenium:
from selenium import webdriver
from selenium_stealth import stealth
driver = webdriver.Chrome()
stealth(driver,
languages=["en-US", "en"],
vendor="Google Inc.",
platform="Win32",
webgl_vendor="Intel Inc.",
renderer="Intel Iris OpenGL Engine",
fix_hairline=True,
)
driver.get('https://example.com')
driver.quit()
When to Use Each Tool
- Undetected ChromeDriver: Best balance of simplicity and effectiveness for Python users
- Playwright: Modern alternative with better performance, good for new projects
- Puppeteer: Node.js projects, extensive ecosystem
- ScraperAPI: When you want managed solution without infrastructure maintenance
- Selenium Wire: When you need to inspect/modify network traffic
- Commercial services: Large-scale scraping, need guaranteed uptime
Compare Python web scraping tools to choose the right one for your project.
Frequently Asked Questions
What is undetected-chromedriver?
Undetected-chromedriver is a Python library that patches Selenium ChromeDriver to bypass anti-bot detection systems. It removes browser automation signatures that websites use to detect bots. The library modifies properties like navigator.webdriver, patches Chrome DevTools Protocol detection points, and makes automated browsers look like real human users. It’s particularly effective against Cloudflare, DataDome, and other common bot detection services. The library is built on top of Selenium, so you use familiar Selenium commands while getting anti-detection features automatically.
Is undetected-chromedriver legal to use?
Yes, undetected-chromedriver itself is legal software, but how you use it determines legality. The library is open-source and doesn’t violate any laws by existing. However, using it to scrape websites that prohibit scraping in their terms of service could violate those terms. Additionally, circumventing technical protection measures might violate laws like the Computer Fraud and Abuse Act in some jurisdictions. Always check website terms of service, respect robots.txt guidelines, and consider the legal implications of web scraping in your specific use case. Learn more about whether web scraping is legal.
Does undetected-chromedriver work with headless mode?
Yes, undetected-chromedriver works with headless mode, but headless browsers are generally easier to detect. You can enable headless mode using options.add_argument('--headless=new') for the new headless implementation. However, many advanced bot detection systems can identify headless browsers through missing browser features, unusual fingerprints, and behavioral patterns. For best anti-detection results, use visible browser mode during development and testing. Only use headless mode in production if you’ve thoroughly tested that it works for your target websites.
Can undetected-chromedriver bypass Cloudflare?
Yes, undetected-chromedriver can bypass many Cloudflare protection levels, but not all. It successfully passes JavaScript challenges and most managed challenges that check for browser automation signatures. However, it may struggle with “I’m Under Attack” mode, interactive CAPTCHAs, and Turnstile challenges. Success depends on factors like your IP reputation, browser fingerprint consistency, and behavioral patterns. Combining undetected-chromedriver with residential proxies, realistic delays, and proper session management significantly improves Cloudflare bypass rates. Some challenges still require manual solving or CAPTCHA solving services.
How is undetected-chromedriver different from regular Selenium?
Undetected-chromedriver differs from regular Selenium by automatically patching bot detection points. Regular Selenium sets navigator.webdriver to true, includes automation extensions, and leaves other fingerprints that websites easily detect. Undetected-chromedriver removes these signatures, patches Chrome DevTools Protocol detection, manages ChromeDriver versions automatically, and implements various anti-detection techniques. You use the same Selenium commands, but the underlying browser behaves more like a real human user. This makes it possible to scrape websites that block standard Selenium instantly.
Do I need proxies with undetected-chromedriver?
No, proxies aren’t always necessary, but they become important for certain scraping scenarios. For small-scale scraping or testing, undetected-chromedriver alone often works fine without proxies. However, proxies become essential when scraping at scale, when your IP gets rate limited or banned, when targeting geo-restricted content, or when dealing with strict IP-based detection. Residential proxies work best because they use real IP addresses that are harder to detect. Datacenter proxies are cheaper but easier to block. Learn about proxy types for web scraping.
Can I use undetected-chromedriver for commercial projects?
Yes, you can use undetected-chromedriver for commercial projects as it’s released under GPL-3.0 license. However, you must comply with the GPL license terms, which include making your source code available if you distribute your application. For commercial use, also consider the legal implications of web scraping itself—ensure you’re not violating website terms of service, copyright laws, or data protection regulations. Many companies successfully use undetected-chromedriver for legitimate business purposes like price monitoring, market research, and competitive analysis.
How do I update ChromeDriver version?
No, you typically don’t need to manually update ChromeDriver with undetected-chromedriver because it handles version management automatically. The library detects your installed Chrome version and downloads the matching ChromeDriver automatically. If you need to force a specific version, use driver = uc.Chrome(version_main=120) replacing 120 with your Chrome major version. To update Chrome itself, simply update through your system’s normal Chrome update process, and undetected-chromedriver will automatically download the appropriate driver next time you run it.
Does undetected-chromedriver work on Linux servers?
Yes, undetected-chromedriver works on Linux servers, but requires Chrome or Chromium installed. Install Chrome on Ubuntu/Debian with sudo apt-get install google-chrome-stable or Chromium with sudo apt-get install chromium-browser. For headless operation on servers without displays, use Xvfb virtual display or the new headless mode. Add flags like --no-sandbox and --disable-dev-shm-usage for Docker containers or limited environments. Many production scrapers run successfully on Linux servers using undetected-chromedriver.
What are the performance implications of using undetected-chromedriver?
Undetected-chromedriver has similar performance to regular Selenium since it’s built on top of it. Browser automation is inherently slower than HTTP requests because it renders full pages with JavaScript, CSS, and images. Expect 2-5 seconds per page minimum. Memory usage can reach 200-500 MB per browser instance. For better performance, disable images and CSS if you don’t need them, use headless mode when possible, implement parallel scraping with multiple instances, and restart drivers periodically to prevent memory leaks. For maximum speed at scale, consider how to speed up web scraping.
Conclusion
Undetected ChromeDriver opens up possibilities for scraping websites that would otherwise block standard automation tools. The key to success is combining the library’s anti-detection features with smart scraping practices.
We’ve covered everything from basic installation and usage to advanced techniques for bypassing Cloudflare, handling authentication, and scraping dynamic content. The most important takeaway is that undetected-chromedriver is just one piece of the puzzle—you also need proper delays, realistic behavior patterns, and ethical scraping practices.
Remember these key principles:
- Always test your scraper thoroughly before running at scale
- Add random delays to mimic human behavior
- Handle errors gracefully and log your activity
- Use proxies when scraping at scale or facing strict limits
- Respect website resources and terms of service
- Keep your Chrome and ChromeDriver versions updated
- Monitor memory usage and restart drivers periodically
The technical capabilities matter, but ethical considerations matter just as much. Use undetected-chromedriver responsibly—scrape only what you need, respect rate limits, and consider the impact on website owners.
Implementing undetected-chromedriver in your scraping projects. Start with simple use cases, test thoroughly, and gradually expand to more complex scenarios. Monitor your success rates and adjust your approach based on what works.
For more web scraping techniques, explore our guides on best Python libraries for web scraping, handling dynamic content, and common web scraping errors.
