Web Scraping

The Complete Guide to Web Scraping With SeleniumBase and Python: Build Faster, Smarter Automation Tools

Web scraping has turned into a must-have skill for developers who need to pull data from websites on autopilot. Traditional tools like Selenium have done the job for years, but let’s be honest—they come with a lot of baggage and complexity. That’s exactly why SeleniumBase is such a breath of fresh air.

SeleniumBase is an all-in-one Python framework built on top of Selenium WebDriver that makes browser automation and web scraping tasks way simpler. It cuts down the amount of repetitive code you have to write, takes care of common automation headaches automatically, and comes with built-in features for stealth mode, CAPTCHA handling, and element detection. Unlike regular Selenium, SeleniumBase needs way fewer lines of code to do the same job while giving you better stability and performance right out of the box.

This guide walks you through everything about web scraping with SeleniumBase and Python. You’ll learn how to set up your environment, move around websites, grab data, handle dynamic content, and dodge detection systems. Whether you’re building a price tracker, collecting research data, or automating boring browser tasks, this tutorial gives you practical examples and best practices for web scraping that actually work in the real world.

Table of Contents

What Is SeleniumBase and Why Should You Use It for Web Scraping?

SeleniumBase is an all-in-one Python framework that extends Selenium WebDriver with simplified syntax, built-in stealth features, and powerful automation capabilities designed specifically for modern web scraping challenges.

Regular Selenium requires a ton of setup and configuration before you can even start scraping. You’ve gotta manually download browser drivers, set up options, handle waits, and write the same code over and over for basic tasks. SeleniumBase gets rid of these headaches by giving you a streamlined API that handles driver management on its own and includes smart features like auto-retry mechanisms and better element detection.

Advantages Over Standard Selenium

From experience, SeleniumBase offers several practical benefits that make it way better than vanilla Selenium for scraping projects:

  • Automatic driver management: No need to download ChromeDriver or GeckoDriver yourself. SeleniumBase does this for you.
  • Built-in stealth mode: Websites can’t easily spot that you’re using automation because SeleniumBase changes browser fingerprints.
  • Simpler syntax: Methods like self.click() and self.type() replace wordy Selenium commands.
  • Smart waiting mechanisms: Waits for elements to be clickable or visible automatically without explicit waits.
  • Visual testing capabilities: Take screenshots, create reports, and check UI elements without extra work.
  • Multi-browser support: Works smoothly with Chrome, Firefox, Edge, and Safari.

Here’s a comparison that shows the difference in code complexity:

❮ Swipe table left/right ❯
FeatureStandard SeleniumSeleniumBase
Driver setupManual download + PATH configurationAutomatic
Element waitExplicit WebDriverWait + Expected ConditionsBuilt-in smart waits
Stealth modeRequires undetected-chromedriver or custom setupNative UC Mode included
Code verbosityHigh (10+ lines for simple tasks)Low (3-5 lines)
CAPTCHA handlingManual integration neededBuilt-in solver support
Screenshot automationManual implementationOne-line command

When to Choose SeleniumBase

SeleniumBase works really well for these scenarios:

  1. Scraping dynamic websites that use lots of JavaScript
  2. E-commerce data extraction from sites like Amazon or Walmart
  3. Login-required scraping where you need to manage cookies and sessions
  4. Testing and validation of web applications with visual elements
  5. Bypassing anti-bot systems that catch standard automation tools

In most cases, SeleniumBase gives you the perfect balance between power and simplicity for Python developers who wanna scrape websites without messing with the technical overhead of configuring Selenium from scratch.

How Do You Install and Set Up SeleniumBase for Python Web Scraping?

You install SeleniumBase using pip with the command pip install seleniumbase, which automatically handles all dependencies including Selenium WebDriver and browser drivers.

The installation process is pretty straightforward compared to traditional Selenium setups. You don’t need to worry about downloading separate driver files or messing with system PATH variables. SeleniumBase manages everything through its built-in driver manager.

Step-by-Step Installation Process

Here’s how the installation works:

1. Install SeleniumBase via pip:

pip install seleniumbase

 

This command installs SeleniumBase along with all the packages it needs. The good news is you don’t need to install Selenium separately because it comes bundled with SeleniumBase.

2. Verify the installation:

seleniumbase --version

 

You should see the version number pop up, which means everything installed correctly.

3. Install browser drivers (optional manual step):

Actually, you can skip this step because SeleniumBase downloads drivers automatically when you run your first script. But if you wanna pre-install them, use:

seleniumbase install chromedriver
seleniumbase install geckodriver

 

4. Test your setup with a quick script:

from seleniumbase import BaseCase

class MyTestClass(BaseCase):
    def test_basic(self):
        self.open("https://www.example.com")
        self.assert_title("Example Domain")

 

Run it with:

pytest test_example.py

 

Setting Up Your First Scraping Project

Let’s set up a proper project structure. In practice, organizing your code from the start saves you headaches later:

my_scraping_project/
│
├── scrapers/
│   ├── __init__.py
│   └── product_scraper.py
├── data/
│   └── output.csv
├── requirements.txt
└── config.py

 

Create a requirements.txt file:

seleniumbase>=4.0.0
pandas>=1.5.0
python-dotenv>=0.20.0

 

Install all dependencies:

pip install -r requirements.txt

 

Worth noting is that SeleniumBase works with Python 3.7 and above. If you’re using an older version, you’ll need to upgrade first.

Configuration Options

SeleniumBase lets you customize how your browser runs. Here are some common configurations:

from seleniumbase import Driver

# Headless mode (browser runs in background)
driver = Driver(browser="chrome", headless=True)

# UC Mode for stealth (bypasses detection)
driver = Driver(uc=True)

# Mobile emulation
driver = Driver(mobile=True)

# Proxy configuration
driver = Driver(proxy="http://proxy-server:8080")

 

In real-world usage, you’ll probably use headless mode for production scraping and visible mode during development so you can see what’s happening.

What Are the Core SeleniumBase Methods for Web Scraping?

SeleniumBase provides simplified methods like self.open(), self.click(), self.type(), and self.get_text() that replace verbose Selenium commands and automatically handle element waiting and error recovery.

The beauty of SeleniumBase is how it turns complicated Selenium operations into simple, readable commands. Instead of writing multiple lines to wait for an element and then interact with it, you just call one method and SeleniumBase handles everything behind the scenes.

These methods help you move around websites:

Opening pages:

from seleniumbase import BaseCase

class Scraper(BaseCase):
    def test_navigation(self):
        # Open a URL
        self.open("https://example.com")
        
        # Navigate back
        self.go_back()
        
        # Navigate forward
        self.go_forward()
        
        # Refresh the page
        self.refresh_page()

 

Switching between tabs:

# Open a new tab
self.open_new_window()

# Switch to a specific tab by index
self.switch_to_window(1)

# Switch to the newest tab
self.switch_to_newest_window()

 

Element Interaction Methods

Here’s how you interact with page elements:

Clicking elements:

# Click a button or link
self.click("button#submit")

# Double click
self.double_click("div.card")

# Right click
self.context_click("img.photo")

 

Typing text:

# Type into an input field
self.type("input#username", "myuser")

# Clear and then type
self.update_text("input#search", "new query")

# Press keys
self.press_keys("input#field", "Hello\n")  # Types Hello and presses Enter

 

Selecting from dropdowns:

# Select by visible text
self.select_option_by_text("select#country", "United States")

# Select by value
self.select_option_by_value("select#size", "large")

 

Data Extraction Methods

These methods grab data from pages:

Getting text content:

# Get text from an element
title = self.get_text("h1.product-title")

# Get attribute value
image_url = self.get_attribute("img.product", "src")

# Get all text from multiple elements
prices = self.get_texts("span.price")

 

Working with tables:

# Get all table data
table_data = self.get_text("table#results")

# Get specific cell
cell_value = self.get_text("table tr:nth-child(2) td:nth-child(3)")

 

Extracting links:

# Get href attribute
link = self.get_attribute("a.download-link", "href")

# Get all links on page
all_links = self.get_elements("a")
for link in all_links:
    url = link.get_attribute("href")
    print(url)

 

Waiting and Checking Methods

SeleniumBase includes smart waiting methods:

Wait for elements:

# Wait for element to be visible
self.wait_for_element_visible("div.content", timeout=10)

# Wait for element to disappear
self.wait_for_element_not_visible("div.loading")

# Wait for text to appear
self.wait_for_text("Success!", "div.message")

 

Check if elements exist:

# Check if element is present
if self.is_element_present("button.subscribe"):
    self.click("button.subscribe")

# Check if text exists
if self.is_text_visible("Out of Stock"):
    print("Product unavailable")

 

Scrolling Methods

Scrolling is often needed for scraping dynamic websites:

# Scroll to element
self.scroll_to("footer")

# Scroll to top
self.scroll_to_top()

# Scroll to bottom
self.scroll_to_bottom()

# Slow scroll (triggers lazy loading)
self.slow_scroll_to_element("div.comments")

 

Screenshot and Visual Methods

Capture what you see:

# Take screenshot of entire page
self.save_screenshot("page.png")

# Take screenshot of specific element
self.save_screenshot("product.png", "div.product-card")

# Create PDF of page
self.save_page_as_pdf("page.pdf")

 

How Do You Handle Dynamic Content and JavaScript-Heavy Websites?

You handle dynamic content by using SeleniumBase’s built-in wait methods, scrolling techniques, and JavaScript execution capabilities that ensure all AJAX-loaded elements are fully rendered before extraction.

Many modern websites load content dynamically using JavaScript. This means the HTML you see in the browser isn’t the same as what you’d get from a simple HTTP request. SeleniumBase excels at handling these situations because it actually runs a real browser that executes JavaScript just like a human visitor would.

Waiting for AJAX Content to Load

The key to scraping dynamic websites is knowing when content has finished loading. Here’s how:

Wait for specific elements:

from seleniumbase import BaseCase

class DynamicScraper(BaseCase):
    def test_ajax_content(self):
        self.open("https://example.com/products")
        
        # Wait for the product list to load
        self.wait_for_element_visible("div.product-list", timeout=15)
        
        # Wait for at least 10 products to appear
        self.wait_for_element_present("div.product-card", timeout=10)
        
        # Now scrape the data
        products = self.get_texts("h3.product-name")

 

Wait for loading spinners to disappear:

# Wait for loading indicator to vanish
self.wait_for_element_not_visible("div.spinner", timeout=20)

# Alternative: wait for absence
self.wait_for_element_absent("div.loading-overlay")

 

Triggering Infinite Scroll

Many websites use infinite scroll to load more content as you scroll down. Here’s how to handle that:

def scrape_infinite_scroll(self):
    self.open("https://example.com/feed")
    
    # Get initial count
    last_count = 0
    current_count = len(self.find_elements("div.post"))
    
    # Keep scrolling until no new content loads
    while current_count > last_count:
        last_count = current_count
        
        # Scroll to bottom
        self.scroll_to_bottom()
        
        # Wait a bit for new content to load
        self.sleep(2)
        
        # Count elements again
        current_count = len(self.find_elements("div.post"))
    
    # Now extract all the data
    posts = self.get_texts("div.post h2.title")

 

Executing JavaScript Directly

Sometimes you need to run custom JavaScript to trigger specific behaviors:

# Execute JavaScript code
self.execute_script("window.scrollTo(0, 1000);")

# Click hidden elements
self.execute_script("arguments[0].click();", element)

# Modify page content
self.execute_script("document.querySelector('div.popup').remove();")

# Get data from JavaScript variables
data = self.execute_script("return window.pageData;")

 

Handling Shadow DOM

Some websites use Shadow DOM, which hides elements from normal selectors:

# Access shadow root elements
shadow_element = self.execute_script(
    "return document.querySelector('custom-element').shadowRoot.querySelector('button')"
)
shadow_element.click()

 

Dealing with Lazy-Loaded Images

Images that load as you scroll need special handling:

def scrape_lazy_images(self):
    self.open("https://example.com/gallery")
    
    # Scroll slowly to trigger lazy loading
    self.slow_scroll_to_bottom()
    
    # Wait for images to load
    self.wait_for_element_visible("img[src*='full-size']", timeout=10)
    
    # Extract image URLs
    images = self.find_elements("img.gallery-image")
    image_urls = [img.get_attribute("src") for img in images]

 

Working with Single Page Applications (SPAs)

SPAs like React or Vue apps need careful timing:

def scrape_spa(self):
    self.open("https://example.com/app")
    
    # Wait for React/Vue to finish rendering
    self.wait_for_element_present("#root div.content")
    
    # Wait for API calls to complete
    self.sleep(3)
    
    # Look for "data loaded" indicators
    self.wait_for_text("Showing 1-20 of 500", "div.results-info")
    
    # Now it's safe to scrape
    items = self.get_texts("li.result-item")

 

Monitoring Network Requests

You can track network activity to know when data has loaded:

from seleniumbase import Driver

driver = Driver(uc=True)
driver.get("https://example.com")

# Wait for specific API endpoint to complete
driver.execute_script("""
    window.apiComplete = false;
    const originalFetch = window.fetch;
    window.fetch = function() {
        return originalFetch.apply(this, arguments).then(response => {
            if (response.url.includes('/api/products')) {
                window.apiComplete = true;
            }
            return response;
        });
    };
""")

# Wait for API flag
driver.execute_script("return window.apiComplete === true")

 

How Do You Avoid Detection When Scraping With SeleniumBase?

You avoid detection by enabling SeleniumBase’s UC Mode with Driver(uc=True), which modifies browser fingerprints, mimics human behavior, and bypasses common anti-bot systems like Cloudflare and DataDome.

Most websites today use sophisticated anti-bot systems to block scrapers. These systems look for telltale signs that you’re using automation—things like missing browser properties, suspicious mouse movements, or WebDriver flags. SeleniumBase’s Undetected Chrome (UC) Mode was built specifically to fly under the radar of these detection systems.

Enabling Stealth Mode (UC Mode)

The easiest way to avoid detection is using UC Mode:

from seleniumbase import Driver

# Basic UC Mode
driver = Driver(uc=True)
driver.get("https://protected-site.com")

# UC Mode with additional options
driver = Driver(
    uc=True,
    headless=False,  # Headless can trigger detection
    incognito=True
)

 

In many cases, simply enabling UC Mode is enough to bypass basic protection systems. It works because SeleniumBase removes automation flags, patches JavaScript properties, and makes your browser look like a regular user’s browser.

Randomizing User Agents

Rotating user agents makes your requests look like they come from different browsers:

user_agents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Safari/605.1.15",
    "Mozilla/5.0 (X11; Linux x86_64) Firefox/121.0"
]

import random
agent = random.choice(user_agents)

driver = Driver(uc=True, agent=agent)

 

Using Proxies to Rotate IP Addresses

Rotating proxies help you avoid IP bans:

# Single proxy
driver = Driver(
    uc=True,
    proxy="http://username:[email protected]:8080"
)

# Rotating through multiple proxies
proxies = [
    "http://proxy1.com:8080",
    "http://proxy2.com:8080",
    "http://proxy3.com:8080"
]

for proxy in proxies:
    driver = Driver(uc=True, proxy=proxy)
    driver.get("https://target-site.com")
    # Scrape data
    driver.quit()

 

To learn more about how to change IP address in Python, check out our dedicated guide.

Mimicking Human Behavior

Real users don’t interact with websites at robot speed. Add realistic delays:

from seleniumbase import BaseCase
import random
import time

class HumanLikeScraper(BaseCase):
    def test_human_behavior(self):
        self.open("https://example.com")
        
        # Random delay before interacting
        time.sleep(random.uniform(2, 5))
        
        # Slow typing
        self.slow_click("input#search")
        self.type("input#search", "product name", typing_speed=50)
        
        # Random mouse movements
        self.hover("nav a")
        time.sleep(random.uniform(0.5, 2))
        
        # Click with delay
        self.click("button#submit")
        time.sleep(random.uniform(3, 7))

 

Handling CAPTCHAs

While SeleniumBase can’t solve all CAPTCHAs automatically, you have options:

Manual solving during development:

self.open("https://site-with-captcha.com")

# Pause for manual CAPTCHA solving
input("Solve the CAPTCHA and press Enter...")

# Continue scraping
self.click("button#submit")

 

Using CAPTCHA solving services:

# Integration with 2Captcha or similar services
captcha_solution = solve_captcha_via_api(site_key, page_url)
self.execute_script(f"document.getElementById('g-recaptcha-response').innerHTML='{captcha_solution}';")
self.click("button#submit")

 

For more details, read our guide on bypassing CAPTCHA verification in web scraping.

Avoiding Common Detection Patterns

Here are things that trigger anti-bot systems:

Don’t do this:

  • Open too many pages too quickly
  • Use headless mode on heavily protected sites
  • Keep the exact same timing between requests
  • Ignore robots.txt guidelines

Do this instead:

  • Add random delays between 2-8 seconds
  • Use visible browser mode for critical sites
  • Vary your navigation patterns
  • Respect rate limits

Checking If Your Scraper Is Detected

Test your stealth configuration:

def test_detection(self):
    # Visit bot detection test site
    self.open("https://bot.sannysoft.com/")
    self.sleep(3)
    
    # Take screenshot to see results
    self.save_screenshot("detection_test.png")
    
    # Check for WebDriver flag
    webdriver_present = self.execute_script("return navigator.webdriver;")
    print(f"WebDriver detected: {webdriver_present}")

 

Handling Cloudflare Protection

Cloudflare is one of the toughest anti-bot systems. Here’s how SeleniumBase handles it:

from seleniumbase import Driver

driver = Driver(uc=True)
driver.uc_open_with_reconnect("https://cloudflare-protected-site.com", 4)
driver.uc_gui_click_captcha()

 

The uc_open_with_reconnect() method was specifically designed to handle Cloudflare challenges. Learn more about Cloudflare error codes and how to handle them.

How Do You Extract and Structure Data From Scraped Web Pages?

You extract data by selecting elements with CSS selectors or XPath, retrieving text or attributes with SeleniumBase methods, and then organizing the results into structured formats like dictionaries, lists, or DataFrames.

Getting the data is only half the battle. The real skill is pulling out exactly what you need and organizing it in a way that’s useful. SeleniumBase makes this easier with simple methods for finding and extracting information from HTML elements.

Using CSS Selectors vs XPath

You’ve got two main ways to locate elements:

CSS Selectors (recommended for most cases):

# By ID
self.get_text("#product-title")

# By class
self.get_text(".price-value")

# By attribute
self.get_text("input[name='email']")

# Nested selection
self.get_text("div.product > h2.title")

# Nth child
self.get_text("ul.items li:nth-child(3)")

 

XPath (better for complex selections):

# Text contains
self.get_text("//span[contains(text(), 'Price:')]")

# Following sibling
self.get_text("//label[text()='Email:']/following-sibling::input")

# Parent selection
self.get_text("//button[@type='submit']/parent::form")

 

In practice, CSS selectors are easier to read and faster to write. Use XPath when you need more complex logic.

Extracting Single vs Multiple Elements

Here’s the difference:

Single element:

# Get one element
title = self.get_text("h1.main-title")
price = self.get_text("span.price")
image = self.get_attribute("img.product-image", "src")

 

Multiple elements:

# Get all matching elements
all_titles = self.get_texts("h2.product-name")
all_prices = self.get_texts("span.price")
all_links = []

links = self.find_elements("a.product-link")
for link in links:
    url = link.get_attribute("href")
    all_links.append(url)

 

Building Structured Data

Let’s turn scraped content into organized data:

Simple list structure:

from seleniumbase import BaseCase

class ProductScraper(BaseCase):
    def test_scrape_products(self):
        self.open("https://example.com/products")
        
        products = []
        
        # Find all product cards
        cards = self.find_elements("div.product-card")
        
        for card in cards:
            product = {
                "name": card.find_element("css selector", "h3.title").text,
                "price": card.find_element("css selector", "span.price").text,
                "rating": card.find_element("css selector", "div.rating").get_attribute("data-rating"),
                "image": card.find_element("css selector", "img").get_attribute("src")
            }
            products.append(product)
        
        print(f"Scraped {len(products)} products")
        return products

 

Dictionary with categories:

def scrape_categorized_data(self):
    self.open("https://example.com/categories")
    
    data = {}
    
    categories = self.find_elements("div.category")
    
    for category in categories:
        cat_name = category.find_element("css selector", "h2").text
        items = category.find_elements("css selector", "li.item")
        
        data[cat_name] = [item.text for item in items]
    
    return data

 

Cleaning Extracted Data

Raw scraped data usually needs cleaning:

def clean_price(price_text):
    # Remove currency symbols and convert to float
    # "$1,299.99" -> 1299.99
    import re
    cleaned = re.sub(r'[^0-9.]', '', price_text)
    return float(cleaned)

def clean_text(text):
    # Remove extra whitespace
    return ' '.join(text.split())

# Usage
raw_price = self.get_text("span.price")  # "$1,299.99"
clean_price_value = clean_price(raw_price)  # 1299.99

raw_description = self.get_text("p.description")
clean_description = clean_text(raw_description)

 

Exporting Data to Different Formats

Save to CSV:

import csv

def save_to_csv(self, data, filename="output.csv"):
    keys = data[0].keys()
    
    with open(filename, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=keys)
        writer.writeheader()
        writer.writerows(data)
    
    print(f"Data saved to {filename}")

 

Save to JSON:

import json

def save_to_json(self, data, filename="output.json"):
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    
    print(f"Data saved to {filename}")

 

Save to pandas DataFrame:

import pandas as pd

def save_to_dataframe(self, data):
    df = pd.DataFrame(data)
    
    # Save to Excel
    df.to_excel("output.xlsx", index=False)
    
    # Save to CSV
    df.to_csv("output.csv", index=False)
    
    # Basic stats
    print(df.describe())
    
    return df

 

Handling Missing Data

Not all elements exist on every page:

def safe_extract(self, selector, attribute=None):
    try:
        if attribute:
            return self.get_attribute(selector, attribute)
        else:
            return self.get_text(selector)
    except Exception:
        return None

# Usage
title = self.safe_extract("h1.title") or "No title"
rating = self.safe_extract("div.rating", "data-rating") or "0"

 

Complete Extraction Example

Here’s a full example that scrapes and structures data:

from seleniumbase import BaseCase
import pandas as pd

class EcommerceScraper(BaseCase):
    def test_scrape_store(self):
        self.open("https://example-store.com/products")
        
        # Wait for products to load
        self.wait_for_element_visible("div.product-grid")
        
        products = []
        
        # Get all product elements
        items = self.find_elements("div.product-item")
        
        for item in items:
            try:
                product = {
                    "name": item.find_element("css selector", "h3.name").text,
                    "price": self.extract_price(item),
                    "rating": self.extract_rating(item),
                    "availability": self.check_stock(item),
                    "url": item.find_element("css selector", "a").get_attribute("href")
                }
                products.append(product)
            except Exception as e:
                print(f"Error scraping item: {e}")
                continue
        
        # Save to multiple formats
        self.save_results(products)
        
        return products
    
    def extract_price(self, element):
        price_text = element.find_element("css selector", "span.price").text
        return float(price_text.replace('$', '').replace(',', ''))
    
    def extract_rating(self, element):
        try:
            return float(element.find_element("css selector", "div.rating").get_attribute("data-rating"))
        except:
            return 0.0
    
    def check_stock(self, element):
        try:
            stock_element = element.find_element("css selector", "span.stock")
            return "In Stock" in stock_element.text
        except:
            return False
    
    def save_results(self, data):
        # Save to CSV
        pd.DataFrame(data).to_csv("products.csv", index=False)
        
        # Save to JSON
        import json
        with open("products.json", 'w') as f:
            json.dump(data, f, indent=2)
        
        print(f"Saved {len(data)} products to CSV and JSON")

 

How Do You Handle Login and Authentication in Web Scraping?

You handle login by navigating to the login page, filling in credentials with self.type(), clicking the submit button, and then saving cookies for future sessions to avoid repeated logins.

Many valuable websites require you to log in before accessing data. Scraping websites that require login involves managing authentication, handling sessions, and storing cookies properly. SeleniumBase makes this easier than traditional approaches.

Basic Login Flow

Here’s the standard process:

from seleniumbase import BaseCase

class LoginScraper(BaseCase):
    def test_login_and_scrape(self):
        # Navigate to login page
        self.open("https://example.com/login")
        
        # Fill in credentials
        self.type("input#email", "[email protected]")
        self.type("input#password", "your-password")
        
        # Click login button
        self.click("button[type='submit']")
        
        # Wait for login to complete
        self.wait_for_element_visible("div.dashboard")
        
        # Now you're logged in and can scrape protected pages
        self.open("https://example.com/protected-data")
        data = self.get_text("div.data-container")

 

Saving and Loading Cookies

Instead of logging in every time, save your session cookies:

import pickle

def test_save_cookies(self):
    # Login once
    self.open("https://example.com/login")
    self.type("input#email", "[email protected]")
    self.type("input#password", "password123")
    self.click("button#login")
    self.wait_for_element("div.dashboard")
    
    # Save cookies to file
    cookies = self.driver.get_cookies()
    with open("cookies.pkl", "wb") as f:
        pickle.dump(cookies, f)
    
    print("Cookies saved!")

def test_load_cookies(self):
    # Load saved cookies
    self.open("https://example.com")
    
    with open("cookies.pkl", "rb") as f:
        cookies = pickle.load(f)
    
    for cookie in cookies:
        self.driver.add_cookie(cookie)
    
    # Refresh to apply cookies
    self.refresh_page()
    
    # Now you're logged in without entering credentials
    self.open("https://example.com/protected-data")

 

Our guide on managing cookies and sessions in web scrapers goes deeper into this topic.

Handling Two-Factor Authentication (2FA)

2FA adds complexity, but you can handle it:

def test_login_with_2fa(self):
    self.open("https://example.com/login")
    
    # Enter credentials
    self.type("input#username", "[email protected]")
    self.type("input#password", "password123")
    self.click("button#login")
    
    # Wait for 2FA prompt
    self.wait_for_element_visible("input#2fa-code")
    
    # Pause for manual 2FA entry
    print("Please enter your 2FA code in the browser")
    input("Press Enter after entering the code...")
    
    # Wait for dashboard
    self.wait_for_element_visible("div.dashboard")
    
    # Save cookies for next time
    self.save_cookies_to_file()

 

For automated 2FA, you’d need to integrate with authenticator apps via their APIs.

Different Authentication Types

Form-based authentication (most common):

self.type("input[name='username']", "myuser")
self.type("input[name='password']", "mypass")
self.click("button#submit")

 

HTTP Basic Auth:

# Include credentials in URL
self.open("https://username:[email protected]/protected")

 

OAuth login (Google, Facebook, etc.):

def test_oauth_login(self):
    self.open("https://example.com/login")
    
    # Click "Login with Google"
    self.click("button#google-login")
    
    # Wait for Google login popup
    self.switch_to_newest_window()
    
    # Enter Google credentials
    self.type("input[type='email']", "[email protected]")
    self.click("button#next")
    self.wait_for_element("input[type='password']")
    self.type("input[type='password']", "password")
    self.click("button#next")
    
    # Switch back to main window
    self.switch_to_window(0)
    
    # Wait for redirect back to site
    self.wait_for_element("div.dashboard")

 

Session Management Best Practices

Keep these tips in mind:

Check if already logged in:

def ensure_logged_in(self):
    self.open("https://example.com/dashboard")
    
    # If redirected to login page, you're not logged in
    if "/login" in self.get_current_url():
        self.perform_login()
    else:
        print("Already logged in")

 

Handle session expiration:

def scrape_with_retry(self):
    max_retries = 3
    
    for attempt in range(max_retries):
        try:
            self.open("https://example.com/data")
            
            # Check if session expired
            if self.is_element_visible("div.session-expired"):
                print("Session expired, logging in again...")
                self.perform_login()
                continue
            
            # Scrape data
            data = self.get_text("div.content")
            return data
            
        except Exception as e:
            print(f"Attempt {attempt + 1} failed: {e}")
            if attempt < max_retries - 1:
                self.perform_login()

 

Rotate accounts to avoid bans:

accounts = [
    {"email": "[email protected]", "password": "pass1"},
    {"email": "[email protected]", "password": "pass2"},
    {"email": "[email protected]", "password": "pass3"}
]

def scrape_with_multiple_accounts(self):
    for account in accounts:
        self.perform_login(account["email"], account["password"])
        data = self.scrape_data()
        self.save_data(data)
        self.logout()

 

Handling Login Errors

Deal with common login problems:

def robust_login(self, email, password):
    self.open("https://example.com/login")
    
    self.type("input#email", email)
    self.type("input#password", password)
    self.click("button#login")
    
    # Wait a bit for response
    self.sleep(2)
    
    # Check for error messages
    if self.is_element_visible("div.error-message"):
        error = self.get_text("div.error-message")
        print(f"Login failed: {error}")
        return False
    
    # Check for CAPTCHA
    if self.is_element_visible("div.captcha"):
        print("CAPTCHA detected - manual solving needed")
        input("Solve CAPTCHA and press Enter...")
    
    # Verify successful login
    if self.is_element_visible("div.dashboard", timeout=10):
        print("Login successful")
        return True
    else:
        print("Login failed - unknown error")
        return False

 

What Are the Best Practices for Error Handling and Data Validation?

Best practices include wrapping scraping operations in try-except blocks, validating extracted data against expected formats, implementing retry logic for failed requests, and logging errors with context for debugging.

Web scraping isn’t always smooth. Pages change, networks fail, elements disappear, and unexpected errors pop up. The difference between a fragile scraper that breaks constantly and a robust one that runs reliably comes down to proper error handling.

Implementing Try-Except Blocks

Always wrap risky operations:

from seleniumbase import BaseCase

class RobustScraper(BaseCase):
    def test_scrape_with_error_handling(self):
        try:
            self.open("https://example.com/products")
            self.wait_for_element_visible("div.product-list", timeout=10)
            
            products = self.scrape_products()
            self.save_to_file(products)
            
        except Exception as e:
            print(f"Scraping failed: {e}")
            self.save_screenshot("error.png")
            raise
    
    def scrape_products(self):
        products = []
        
        items = self.find_elements("div.product")
        
        for item in items:
            try:
                product = self.extract_product_data(item)
                products.append(product)
            except Exception as e:
                print(f"Failed to extract product: {e}")
                continue  # Skip this item and continue
        
        return products

 

Retry Logic for Failed Operations

Don’t give up after one failure:

import time
from functools import wraps

def retry(max_attempts=3, delay=2):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_attempts - 1:
                        raise
                    print(f"Attempt {attempt + 1} failed: {e}. Retrying in {delay}s...")
                    time.sleep(delay)
        return wrapper
    return decorator

class RetryingScraper(BaseCase):
    @retry(max_attempts=3, delay=5)
    def test_scrape_with_retry(self):
        self.open("https://example.com/data")
        return self.get_text("div.content")

 

Validating Scraped Data

Make sure your data makes sense:

def validate_product(product):
    """Validate product data before saving"""
    errors = []
    
    # Check required fields
    if not product.get("name"):
        errors.append("Missing product name")
    
    if not product.get("price"):
        errors.append("Missing price")
    
    # Validate price format
    try:
        price = float(product["price"])
        if price <= 0:
            errors.append("Invalid price (must be positive)")
    except (ValueError, TypeError):
        errors.append("Price is not a valid number")
    
    # Validate URL format
    if product.get("url"):
        if not product["url"].startswith("http"):
            errors.append("Invalid URL format")
    
    return len(errors) == 0, errors

def scrape_products_with_validation(self):
    products = []
    invalid_count = 0
    
    items = self.find_elements("div.product")
    
    for item in items:
        try:
            product = self.extract_product_data(item)
            
            # Validate before adding
            is_valid, errors = validate_product(product)
            
            if is_valid:
                products.append(product)
            else:
                print(f"Invalid product: {errors}")
                invalid_count += 1
                
        except Exception as e:
            print(f"Extraction error: {e}")
            continue
    
    print(f"Scraped {len(products)} valid products, {invalid_count} invalid")
    return products

 

Logging for Debugging

Good logs help you figure out what went wrong:

import logging
from datetime import datetime

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(f'scraper_{datetime.now().strftime("%Y%m%d")}.log'),
        logging.StreamHandler()
    ]
)

class LoggingScraper(BaseCase):
    def test_scrape_with_logging(self):
        logging.info("Starting scraping session")
        
        try:
            self.open("https://example.com")
            logging.info(f"Opened {self.get_current_url()}")
            
            products = self.scrape_products()
            logging.info(f"Successfully scraped {len(products)} products")
            
            self.save_to_file(products)
            logging.info("Data saved successfully")
            
        except Exception as e:
            logging.error(f"Scraping failed: {e}", exc_info=True)
            self.save_screenshot("error.png")
            raise
    
    def scrape_products(self):
        products = []
        
        try:
            items = self.find_elements("div.product")
            logging.info(f"Found {len(items)} product elements")
            
            for idx, item in enumerate(items):
                try:
                    product = self.extract_product_data(item)
                    products.append(product)
                    
                    if (idx + 1) % 10 == 0:
                        logging.info(f"Processed {idx + 1} products")
                        
                except Exception as e:
                    logging.warning(f"Failed to extract product {idx}: {e}")
                    continue
                    
        except Exception as e:
            logging.error(f"Product scraping error: {e}")
            raise
            
        return products

 

Handling Timeouts

Set reasonable timeouts and handle them gracefully:

from selenium.common.exceptions import TimeoutException

def scrape_with_timeout(self):
    try:
        # Set page load timeout
        self.driver.set_page_load_timeout(30)
        
        self.open("https://slow-site.com")
        
        # Wait for element with timeout
        self.wait_for_element_visible("div.content", timeout=15)
        
    except TimeoutException:
        print("Page took too long to load")
        
        # Try alternative approach
        self.execute_script("window.stop();")  # Stop loading
        
        # Check if minimum content loaded
        if self.is_element_present("div.main"):
            print("Partial content loaded, continuing...")
        else:
            print("No content loaded, skipping")
            return None

 

Handling Common Scraping Errors

Here’s how to deal with typical problems:

from selenium.common.exceptions import (
    NoSuchElementException,
    StaleElementReferenceException,
    ElementClickInterceptedException
)

def robust_element_interaction(self):
    # Handle missing elements
    try:
        element = self.find_element("div.product")
    except NoSuchElementException:
        print("Element not found - might be on wrong page")
        return None
    
    # Handle stale elements (DOM changed)
    try:
        text = element.text
    except StaleElementReferenceException:
        print("Element became stale, re-finding it")
        element = self.find_element("div.product")
        text = element.text
    
    # Handle blocked clicks
    try:
        self.click("button#submit")
    except ElementClickInterceptedException:
        print("Click blocked by overlay, trying JavaScript click")
        self.execute_script("arguments[0].click();", element)

 

Creating a Complete Error-Resistant Scraper

Here’s everything put together:

import logging
from seleniumbase import BaseCase
import json
from datetime import datetime

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ProductionScraper(BaseCase):
    def test_production_scrape(self):
        results = {
            "timestamp": datetime.now().isoformat(),
            "products": [],
            "errors": [],
            "stats": {}
        }
        
        try:
            self.setup_scraper()
            products = self.scrape_all_pages()
            
            # Validate and save
            valid_products = self.validate_and_clean(products)
            results["products"] = valid_products
            results["stats"] = {
                "total_scraped": len(products),
                "valid": len(valid_products),
                "invalid": len(products) - len(valid_products)
            }
            
            self.save_results(results)
            logger.info(f"Scraping completed: {results['stats']}")
            
        except Exception as e:
            logger.error(f"Fatal error: {e}", exc_info=True)
            results["errors"].append(str(e))
            self.save_screenshot("fatal_error.png")
            
        finally:
            # Always save what we got
            if results["products"]:
                self.save_results(results)
    
    def setup_scraper(self):
        logger.info("Setting up scraper")
        self.driver.set_page_load_timeout(30)
        self.open("https://example.com")
    
    def scrape_all_pages(self):
        all_products = []
        page = 1
        max_pages = 10
        
        while page <= max_pages:
            try:
                logger.info(f"Scraping page {page}")
                products = self.scrape_current_page()
                all_products.extend(products)
                
                if not self.go_to_next_page():
                    break
                    
                page += 1
                
            except Exception as e:
                logger.error(f"Error on page {page}: {e}")
                break
        
        return all_products
    
    def validate_and_clean(self, products):
        valid = []
        
        for product in products:
            try:
                if self.is_valid_product(product):
                    cleaned = self.clean_product(product)
                    valid.append(cleaned)
            except Exception as e:
                logger.warning(f"Validation error: {e}")
                continue
        
        return valid
    
    def save_results(self, results):
        filename = f"results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(filename, 'w') as f:
            json.dump(results, f, indent=2)
        logger.info(f"Results saved to {filename}")

 

How Do You Scale and Optimize SeleniumBase Web Scrapers?

You scale SeleniumBase scrapers by implementing parallel execution with pytest-xdist, using headless mode to reduce resource consumption, and optimizing selectors and wait times to improve speed and efficiency.

Once you’ve got a working scraper, the next challenge is making it faster and able to handle larger volumes. A scraper that takes hours to collect data from 1,000 pages isn’t practical. Let’s look at how to speed up web scraping with SeleniumBase.

Running Multiple Browsers in Parallel

Parallel processing is the fastest way to scale:

# Install pytest-xdist first
# pip install pytest-xdist

# Run with multiple workers
# pytest test_scraper.py -n 4

from seleniumbase import BaseCase

class ParallelScraper(BaseCase):
    def test_scrape_page_1(self):
        self.scrape_category("electronics")
    
    def test_scrape_page_2(self):
        self.scrape_category("clothing")
    
    def test_scrape_page_3(self):
        self.scrape_category("books")
    
    def scrape_category(self, category):
        self.open(f"https://example.com/{category}")
        # Scraping logic here

 

Run this with:

pytest test_scraper.py -n 4 --headless

 

This runs 4 browsers simultaneously, which can be 4x faster.

Using Headless Mode

Headless browsers run without a visible window, using less memory and CPU:

from seleniumbase import Driver

# Headless Chrome
driver = Driver(browser="chrome", headless=True)

# Or in test mode
class HeadlessScraper(BaseCase):
    def test_scrape(self):
        # Run with --headless flag
        self.open("https://example.com")

 

Command line:

pytest test_scraper.py --headless

 

Headless mode is usually 20-30% faster and uses 40% less memory.

Optimizing Selector Performance

Faster selectors mean faster scraping:

Slow selectors:

# XPath with complex logic (slow)
self.find_element("//div[@class='container']//span[contains(text(), 'Price')]")

# Searching entire page (slow)
self.find_elements("*")

 

Fast selectors:

# ID selector (fastest)
self.find_element("#price")

# Class selector (fast)
self.find_element(".price-value")

# Direct CSS path (fast)
self.find_element("div.product > span.price")

 

Reducing Wait Times

Don’t wait longer than necessary:

# Bad: Fixed long waits
self.sleep(10)  # Always waits 10 seconds

# Good: Smart waits with shorter timeout
self.wait_for_element_visible("div.content", timeout=5)

# Better: Check if already present
if self.is_element_visible("div.content"):
    # Element already there, no waiting
    text = self.get_text("div.content")
else:
    self.wait_for_element_visible("div.content", timeout=5)

 

Disabling Unnecessary Features

Turn off what you don’t need:

from selenium.webdriver.chrome.options import Options

options = Options()

# Disable images (saves bandwidth and time)
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)

# Disable CSS
prefs["profile.managed_default_content_settings.stylesheets"] = 2

# Disable JavaScript (only if site works without it)
prefs["profile.managed_default_content_settings.javascript"] = 2

driver = Driver(browser="chrome", options=options)

 

Worth noting is that disabling JavaScript breaks most modern websites, so test carefully.

Implementing Smart Caching

Don’t scrape the same data twice:

import json
import os
from datetime import datetime, timedelta

class CachingScraper(BaseCase):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.cache_file = "scraper_cache.json"
        self.cache_duration = timedelta(hours=24)
    
    def get_cached_data(self, url):
        if not os.path.exists(self.cache_file):
            return None
        
        with open(self.cache_file, 'r') as f:
            cache = json.load(f)
        
        if url in cache:
            cached_time = datetime.fromisoformat(cache[url]["timestamp"])
            
            if datetime.now() - cached_time < self.cache_duration:
                print(f"Using cached data for {url}")
                return cache[url]["data"]
        
        return None
    
    def save_to_cache(self, url, data):
        cache = {}
        if os.path.exists(self.cache_file):
            with open(self.cache_file, 'r') as f:
                cache = json.load(f)
        
        cache[url] = {
            "timestamp": datetime.now().isoformat(),
            "data": data
        }
        
        with open(self.cache_file, 'w') as f:
            json.dump(cache, f)
    
    def scrape_with_cache(self, url):
        # Check cache first
        cached = self.get_cached_data(url)
        if cached:
            return cached
        
        # Not in cache, scrape it
        self.open(url)
        data = self.get_text("div.content")
        
        # Save to cache
        self.save_to_cache(url, data)
        
        return data

 

Managing Memory Usage

Reduce memory usage when scraping many pages:

def scrape_many_pages(self):
    urls = [f"https://example.com/page/{i}" for i in range(1, 1001)]
    
    batch_size = 50
    
    for i in range(0, len(urls), batch_size):
        batch = urls[i:i+batch_size]
        
        # Process batch
        for url in batch:
            self.open(url)
            data = self.extract_data()
            self.save_data(data)
        
        # Clear browser cache and restart
        if i % 200 == 0:
            self.driver.quit()
            self.driver = self.get_new_driver()
            print(f"Restarted browser after {i} pages")

 

Database Storage for Large Datasets

For big scraping projects, use a database instead of JSON files:

import sqlite3

class DatabaseScraper(BaseCase):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setup_database()
    
    def setup_database(self):
        self.conn = sqlite3.connect('products.db')
        self.cursor = self.conn.cursor()
        
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS products (
                id INTEGER PRIMARY KEY,
                name TEXT,
                price REAL,
                url TEXT UNIQUE,
                scraped_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        self.conn.commit()
    
    def save_product(self, product):
        try:
            self.cursor.execute('''
                INSERT OR REPLACE INTO products (name, price, url)
                VALUES (?, ?, ?)
            ''', (product['name'], product['price'], product['url']))
            
            self.conn.commit()
        except Exception as e:
            print(f"Database error: {e}")
    
    def get_scraped_urls(self):
        self.cursor.execute('SELECT url FROM products')
        return [row[0] for row in self.cursor.fetchall()]
    
    def close_database(self):
        self.conn.close()

 

Monitoring Performance

Track how your scraper performs:

import time
from functools import wraps

def measure_time(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.2f} seconds")
        return result
    return wrapper

class MonitoredScraper(BaseCase):
    @measure_time
    def test_scrape_with_monitoring(self):
        self.open("https://example.com")
        
        start_products = time.time()
        products = self.scrape_products()
        end_products = time.time()
        
        print(f"Scraped {len(products)} products in {end_products - start_products:.2f}s")
        print(f"Average: {(end_products - start_products) / len(products):.2f}s per product")
        
        return products

 

What Are Common Challenges and How Do You Solve Them?

Common challenges include handling dynamic content, avoiding detection, managing rate limits, dealing with CAPTCHAs, and handling inconsistent page structures—each requires specific strategies like smart waits, stealth techniques, and robust error handling.

Every scraper runs into problems. Let’s talk about the most common issues you’ll face and practical ways to solve them.

Challenge 1: Handling Pagination

Many sites split data across multiple pages:

Solution: Automatic pagination handling

def scrape_all_pages(self):
    all_products = []
    page = 1
    
    while True:
        print(f"Scraping page {page}")
        
        # Scrape current page
        products = self.scrape_current_page()
        all_products.extend(products)
        
        # Check if "Next" button exists and is clickable
        if not self.is_element_visible("a.next-page"):
            print("No more pages")
            break
        
        # Check if "Next" button is disabled
        next_button = self.find_element("a.next-page")
        if "disabled" in next_button.get_attribute("class"):
            break
        
        # Go to next page
        self.click("a.next-page")
        self.wait_for_element_visible("div.product-list")
        
        page += 1
        self.sleep(2)  # Be polite
    
    return all_products

 

Challenge 2: Dealing With Rate Limits

Sites often block you if you scrape too fast. Our guide on handling rate limits in web scraping covers this in detail.

Solution: Respectful scraping with delays

import random
import time

def scrape_with_rate_limiting(self):
    urls = self.get_urls_to_scrape()
    
    for idx, url in enumerate(urls):
        # Add random delay between requests
        delay = random.uniform(2, 5)
        print(f"Waiting {delay:.1f}s before request {idx + 1}")
        time.sleep(delay)
        
        try:
            self.open(url)
            data = self.extract_data()
            self.save_data(data)
        except Exception as e:
            print(f"Error on {url}: {e}")
            
            # If rate limited, wait longer
            if "429" in str(e) or "rate limit" in str(e).lower():
                wait_time = 60
                print(f"Rate limited! Waiting {wait_time}s")
                time.sleep(wait_time)

 

Challenge 3: Inconsistent Page Structures

Not all pages have the same HTML structure:

Solution: Flexible extraction with fallbacks

def extract_price_flexible(self, element):
    # Try multiple selectors
    selectors = [
        "span.price-new",
        "div.price",
        "span[itemprop='price']",
        "p.product-price"
    ]
    
    for selector in selectors:
        try:
            price = element.find_element("css selector", selector).text
            if price:
                return self.clean_price(price)
        except:
            continue
    
    # Last resort: search for price pattern in text
    text = element.text
    import re
    match = re.search(r'\$\d+\.\d{2}', text)
    if match:
        return self.clean_price(match.group())
    
    return None

 

Challenge 4: JavaScript-Rendered Content Not Loading

Sometimes content doesn’t load even with waits:

Solution: Multiple waiting strategies

def wait_for_content_multiple_strategies(self):
    self.open("https://example.com/dynamic-page")
    
    # Strategy 1: Wait for specific element
    try:
        self.wait_for_element_visible("div.content", timeout=10)
        return
    except:
        print("Strategy 1 failed")
    
    # Strategy 2: Wait for network idle
    try:
        self.execute_script("""
            return new Promise((resolve) => {
                if (document.readyState === 'complete') {
                    resolve();
                } else {
                    window.addEventListener('load', resolve);
                }
            });
        """)
        self.sleep(2)
        return
    except:
        print("Strategy 2 failed")
    
    # Strategy 3: Scroll to trigger lazy loading
    try:
        self.slow_scroll_to_bottom()
        self.wait_for_element_visible("div.content", timeout=5)
        return
    except:
        print("Strategy 3 failed")
    
    # Strategy 4: Force reload
    self.refresh_page()
    self.wait_for_element_visible("div.content", timeout=10)

 

Challenge 5: Cloudflare and Bot Detection

Sites use Cloudflare to block scrapers. Check our guide on Cloudflare rate limiting.

Solution: Use UC Mode and stealth techniques

from seleniumbase import Driver
import random

def bypass_cloudflare(self):
    driver = Driver(uc=True, headless=False)
    
    try:
        # UC Mode special open
        driver.uc_open_with_reconnect("https://cloudflare-protected-site.com", 4)
        
        # Wait for Cloudflare check
        driver.sleep(5)
        
        # Check if we got through
        if "cloudflare" in driver.current_url.lower():
            print("Cloudflare challenge detected")
            driver.uc_gui_click_captcha()
        
        # Random human-like actions
        driver.execute_script("window.scrollTo(0, 300);")
        driver.sleep(random.uniform(1, 3))
        
        # Now scrape
        content = driver.find_element("css selector", "div.main-content").text
        
    finally:
        driver.quit()
    
    return content

 

Challenge 6: Memory Leaks in Long-Running Scrapers

Browsers eat up memory over time:

Solution: Periodic browser restarts

def scrape_with_memory_management(self):
    urls = self.get_all_urls()  # Could be thousands
    restart_interval = 100
    
    for idx, url in enumerate(urls):
        # Restart browser every N pages
        if idx > 0 and idx % restart_interval == 0:
            print(f"Restarting browser after {idx} pages")
            self.driver.quit()
            self.setUp()  # Reinitialize
        
        try:
            self.open(url)
            data = self.extract_data()
            self.save_data(data)
        except Exception as e:
            print(f"Error on {url}: {e}")
            continue

 

Challenge 7: Handling Pop-ups and Overlays

Annoying pop-ups can block your scraping:

Solution: Auto-dismiss pop-ups

def handle_popups(self):
    # Common pop-up dismissal selectors
    popup_selectors = [
        "button.cookie-accept",
        "button.close-modal",
        "div.overlay button[aria-label='Close']",
        "#newsletter-popup .close",
        "button.gdpr-accept"
    ]
    
    for selector in popup_selectors:
        try:
            if self.is_element_visible(selector, timeout=2):
                self.click(selector)
                print(f"Dismissed pop-up: {selector}")
                self.sleep(1)
        except:
            continue

def scrape_with_popup_handling(self):
    self.open("https://example.com/product")
    
    # Give pop-ups time to appear
    self.sleep(2)
    
    # Dismiss them
    self.handle_popups()
    
    # Now scrape
    data = self.extract_data()
    return data

 

Challenge 8: Mobile vs Desktop Versions

Some sites show different content on mobile:

Solution: Switch between desktop and mobile views

from seleniumbase import Driver

# Desktop scraping
desktop_driver = Driver(browser="chrome", uc=True)

# Mobile scraping
mobile_driver = Driver(browser="chrome", mobile=True, uc=True)

# Or toggle viewport
def scrape_mobile_and_desktop(self):
    # Desktop version
    self.open("https://example.com")
    desktop_data = self.extract_data()
    
    # Switch to mobile viewport
    self.set_window_size(375, 667)  # iPhone size
    self.refresh_page()
    mobile_data = self.extract_data()
    
    return {
        "desktop": desktop_data,
        "mobile": mobile_data
    }

 

How Do You Compare SeleniumBase to Other Web Scraping Tools?

SeleniumBase sits between lightweight libraries like Beautiful Soup and full automation frameworks like Playwright, offering better detection avoidance than vanilla Selenium while being simpler than undetected-chromedriver setups.

Different tools work better for different jobs. Let’s see how SeleniumBase stacks up against other popular scraping options.

SeleniumBase vs Beautiful Soup

Beautiful Soup is a parsing library, not a browser automation tool:

❮ Swipe table left/right ❯
FeatureBeautiful SoupSeleniumBase
JavaScript supportNoYes
SpeedVery fastSlower
Dynamic contentCannot handleExcellent
Setup complexitySimpleModerate
Detection avoidanceN/AExcellent
Login handlingManualEasy
Best forStatic HTMLDynamic sites

When to use Beautiful Soup:

  • Static websites with no JavaScript
  • Fast parsing of HTML you already have
  • Simple data extraction from APIs

When to use SeleniumBase:

  • JavaScript-heavy sites
  • Login-required scraping
  • Sites with anti-bot protection

Learn more in our comparison of best Python libraries for web scraping.

SeleniumBase vs Scrapy

Scrapy is a powerful scraping framework:

❮ Swipe table left/right ❯
FeatureScrapySeleniumBase
JavaScript supportNo (without Splash)Yes
SpeedVery fastModerate
Learning curveSteepGentle
Built-in featuresExtensiveModerate
Browser renderingNoYes
Stealth modeManual setupBuilt-in

When to use Scrapy:

  • Large-scale scraping projects (thousands of pages)
  • Static or API-based sites
  • Need advanced features like distributed scraping

When to use SeleniumBase:

  • Sites requiring browser rendering
  • Smaller to medium projects
  • Need built-in stealth features

Check out our Scrapy vs Selenium vs Beautiful Soup comparison.

SeleniumBase vs Selenium

SeleniumBase is built on Selenium but adds convenience:

❮ Swipe table left/right ❯
FeatureSeleniumSeleniumBase
Driver managementManualAutomatic
Code verbosityHighLow
Stealth featuresRequires pluginsBuilt-in UC Mode
Element waitsManual WebDriverWaitAutomatic
Learning curveModerateEasy
CommunityHugeGrowing

Code comparison:

# Selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://example.com")
element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "div.content"))
)
text = element.text

# SeleniumBase
from seleniumbase import BaseCase

class MyScraper(BaseCase):
    def test_scrape(self):
        self.open("https://example.com")
        text = self.get_text("div.content")

 

Our Selenium web scraping guide covers the standard approach.

SeleniumBase vs Playwright

Playwright is Microsoft’s modern automation tool:

❮ Swipe table left/right ❯
FeaturePlaywrightSeleniumBase
SpeedFasterModerate
Browser supportChrome, Firefox, WebKitChrome, Firefox, Edge
Stealth modeRequires stealth pluginBuilt-in UC Mode
Python integrationExcellentExcellent
CommunityGrowing fastModerate
Testing featuresAdvancedModerate

When to use Playwright:

  • Need WebKit (Safari) support
  • Want faster execution
  • Modern API preferences

When to use SeleniumBase:

  • Need proven stealth capabilities
  • Prefer Selenium-style API
  • Want UC Mode without extra setup

Learn about Playwright stealth for web scraping.

SeleniumBase vs Undetected ChromeDriver

Undetected ChromeDriver focuses purely on stealth:

❮ Swipe table left/right ❯
FeatureUndetected ChromeDriverSeleniumBase
Primary focusAnti-detectionFull automation + stealth
API simplicitySelenium APISimplified API
Built-in featuresMinimalExtensive
MaintenanceActiveVery active
SetupSimpleSimple

When to use Undetected ChromeDriver:

  • Only need stealth, nothing else
  • Comfortable with vanilla Selenium API

When to use SeleniumBase:

  • Want stealth + simplified API + testing features
  • Prefer all-in-one solution

Read more about undetected ChromeDriver in Python.

SeleniumBase vs API Scraping

Sometimes sites offer APIs instead:

When to use APIs instead of SeleniumBase:

  • Official API exists and provides needed data
  • API has reasonable rate limits
  • You want faster, more efficient scraping
  • Legal and ToS considerations

When to use SeleniumBase instead of APIs:

  • No API available
  • API missing critical data
  • API heavily rate-limited or expensive
  • Need to scrape exactly what users see

Learn about web scraping vs API differences.

Decision Matrix

Here’s a quick guide:

Need JavaScript support? 
  No → Use Beautiful Soup or Requests
  Yes → Continue

Large scale (10,000+ pages)?
  Yes → Use Scrapy (+ Splash for JS)
  No → Continue

Need to bypass sophisticated anti-bot?
  Yes → Use SeleniumBase UC Mode
  No → Use Playwright or standard Selenium

Prefer modern async API?
  Yes → Use Playwright
  No → Use SeleniumBase

Want simplest possible code?
  Yes → Use SeleniumBase
  No → Use Selenium

 

Frequently Asked Questions (FAQ)

Is SeleniumBase better than Selenium for web scraping?

Yes, SeleniumBase is better than Selenium for most web scraping projects because it reduces code complexity, includes built-in stealth mode, automatically manages browser drivers, and provides simpler methods for common tasks. While both use the same underlying WebDriver technology, SeleniumBase adds convenience features that save time and make scrapers more reliable. However, if you need very fine-grained control or are working with an existing large Selenium codebase, vanilla Selenium might be preferable.

Can SeleniumBase bypass Cloudflare protection?

Yes, SeleniumBase can bypass Cloudflare protection using its UC Mode (Undetected Chrome Mode). The uc_open_with_reconnect() method specifically handles Cloudflare challenges by modifying browser fingerprints and mimicking human behavior. However, success isn’t guaranteed for all Cloudflare configurations, especially those with stricter security settings. For heavily protected sites, you might need additional techniques like residential proxies or CAPTCHA solving services.

Yes, using SeleniumBase for web scraping is legal, but what you scrape and how you use the data matters. The tool itself is completely legal. However, you must respect website terms of service, copyright laws, and data protection regulations like GDPR. Scraping publicly available data for personal research or analysis is generally acceptable, but commercial use requires more careful legal consideration. Always check robots.txt files and review our guide on how to scrape data from websites legally.

Does SeleniumBase work in headless mode?

Yes, SeleniumBase fully supports headless mode where browsers run without a visible window. You can enable it with Driver(headless=True) or by adding the --headless flag when running tests. Headless mode uses less memory and CPU, making it ideal for production environments and cloud deployments. Keep in mind that some anti-bot systems can detect headless browsers, so for heavily protected sites, you might want to use visible mode with UC Mode enabled.

How do I handle CAPTCHAs when using SeleniumBase?

SeleniumBase cannot automatically solve CAPTCHAs without additional services. For development and testing, you can pause your script with input("Solve CAPTCHA and press Enter...") to solve manually. For production, you’ll need to integrate third-party CAPTCHA solving services like 2Captcha, Anti-Captcha, or CapSolver through their APIs. SeleniumBase’s UC Mode can help you avoid many CAPTCHA challenges altogether by making your scraper less detectable. Learn more in our guide on bypassing CAPTCHA verification.

Can I use proxies with SeleniumBase?

Yes, SeleniumBase supports proxy configuration through the proxy parameter when creating a Driver instance: Driver(proxy="http://proxy-server:8080"). This works with HTTP, HTTPS, and SOCKS proxies. For more advanced scenarios, you can rotate proxies between requests by creating new Driver instances with different proxy settings. Using residential proxies or rotating proxies helps avoid IP bans when scraping at scale.

How fast is SeleniumBase compared to other tools?

SeleniumBase is slower than lightweight libraries like Beautiful Soup or Scrapy but comparable to other browser automation tools. Because it runs an actual browser that renders JavaScript, it takes 2-5 seconds per page on average. However, you can speed up web scraping with headless mode, parallel execution, and optimized selectors. For static sites, Beautiful Soup might be 10x faster, but for JavaScript-heavy sites, SeleniumBase is often the only viable option.

What’s the difference between UC Mode and regular mode?

UC Mode (Undetected Chrome Mode) modifies browser properties to avoid bot detection, while regular mode runs a standard Chrome browser. In UC Mode, SeleniumBase removes automation flags like navigator.webdriver, patches JavaScript properties, and mimics human browser characteristics. This makes your scraper undetectable to most anti-bot systems. Regular mode is fine for non-protected sites and is slightly faster, but UC Mode is essential for sites with Cloudflare, DataDome, or similar protection.

Can SeleniumBase scrape data from login-protected websites?

Yes, SeleniumBase excels at scraping login-protected websites. You can automate the login process by typing credentials into form fields, clicking submit buttons, and then saving session cookies for future use. This makes it perfect for scraping websites that require login. SeleniumBase’s cookie management features let you save authentication cookies to a file and reload them in future sessions, avoiding the need to log in every time.

Is SeleniumBase suitable for scraping large e-commerce sites?

Yes, but with proper optimization and ethical practices. SeleniumBase can scrape sites like Amazon, eBay, and Walmart, but you need to implement rate limiting, use headless mode, rotate proxies, and respect the site’s robots.txt guidelines. Running multiple instances in parallel with pytest-xdist helps scale up. For very large projects (100,000+ pages), consider combining SeleniumBase with a database for storage and implementing checkpointing to resume interrupted scrapes.

Does SeleniumBase require programming experience?

No advanced programming is needed, but basic Python knowledge is required. If you understand Python fundamentals like variables, loops, and functions, you can learn SeleniumBase quickly. The API is designed to be beginner-friendly with readable method names like self.click() and self.type(). The learning curve is gentler than vanilla Selenium. Most people can write their first working scraper within a few hours of reading documentation and examples.

Can I run SeleniumBase on cloud platforms like AWS or Heroku?

Yes, SeleniumBase works on cloud platforms with proper configuration. You’ll need to install Chrome/Chromium and run in headless mode since most cloud servers don’t have displays. For AWS EC2, use an Ubuntu AMI and install required dependencies. For Heroku, add the Chrome buildpack. Docker containers work well for consistent deployment across different platforms. Keep in mind that some cloud platforms have limitations on browser automation, so test thoroughly before deploying production scrapers.

Conclusion

SeleniumBase has become one of the most practical tools for Python web scraping because it solves real problems that developers face every day. Instead of wrestling with driver management, writing repetitive wait logic, or manually configuring stealth features, you get a streamlined framework that handles these headaches automatically.

Throughout this guide, we’ve covered everything from basic installation to advanced techniques like avoiding detection, handling authentication, and scaling your scrapers. The key to success with SeleniumBase is starting simple and gradually adding complexity as your needs grow. Begin with a small scraping task, master the core methods, then expand into parallel execution and stealth features.

The most important takeaway is that web scraping isn’t just about extracting data—it’s about doing it reliably, ethically, and efficiently. Always respect robots.txt files, implement rate limiting, and follow ethical web scraping guidelines. The websites you’re scraping are run by real people with real infrastructure costs.

From here, the best way to learn is by building actual projects. Start with a site you visit regularly and extract something useful—product prices, news headlines, or research data. Each project will teach you new techniques and help you understand how different websites handle automation. Keep experimenting, read the SeleniumBase documentation, and join the community to learn from other developers.

The future of web scraping is moving toward more sophisticated anti-bot systems, which means tools like SeleniumBase with built-in stealth capabilities will become even more valuable. Stay updated on new features, keep learning about how AI is changing web scraping, and always adapt your techniques to changing web technologies.

Now it’s your turn to build something. Take the code examples from this guide, modify them for your specific needs, and start scraping. The data you need is out there—SeleniumBase gives you the tools to get it.

Data Prixa

Data Prixa

Dataprixa is an independent editorial platform focused on data infrastructure and security insights. The content published under this author explores web scraping, data collection, proxy networks, and cybersecurity technologies with an emphasis on clarity, ethical practices, and long-term relevance. Articles are written to support developers, researchers, and modern businesses in understanding data-driven systems and secure infrastructure.