Python & Data Science

Selenium For Data Collection Scraping The Sites Be

You’ve spent hours crafting a BeautifulSoup scraper. You run it, and… nothing. The table is empty. The page just says ‘Loading…’. The data you need — prices, reviews, job listings — is invisible in the HTML you downloaded.

What do you do when the data isn’t in the HTML?

This is the moment every data collector hits. Modern websites built with React, Angular, or Vue don’t ship their content in the initial HTML. They send a bare-bones shell, then use JavaScript to fill it in. BeautifulSoup and Scrapy are excellent at parsing static HTML, but they cannot run JavaScript. They’re like trying to read a book that hasn’t been printed yet.

Here’s a quick example of the problem. Imagine you try to scrape a simple quote page with requests and BeautifulSoup:

import requests
from bs4 import BeautifulSoup

url = 'https://quotes.toscrape.com/js/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Try to find a quote
quotes = soup.find_all('div', class_='quote')
print(f'Number of quotes found: {len(quotes)}')
# Output: Number of quotes found: 0

The page exists. The quotes are there if you open it in a browser. But requests gets an empty shell. The quotes load via JavaScript after the page loads.

Selenium fixes this. It controls a real browser that runs JavaScript, just like a human would. It’s slower and heavier than BeautifulSoup, but for dynamic sites, it’s the only way to get the data.

What Is Selenium? (The Robot in Your Browser)

Imagine you could write a script that controls a web browser exactly as a human would — clicking, scrolling, typing, waiting. That’s Selenium.

Selenium is a browser automation framework. It drives a real browser — Chrome, Firefox, Edge — and can execute JavaScript, wait for elements to appear, and interact with the page.

Think of it this way: BeautifulSoup parses static HTML that you give it. Selenium generates that HTML by running the page in a browser first. It’s like the difference between reading a printed newspaper and watching the news broadcast live.

Let’s see what happens with a minimal “hello world” script:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

# Set up the Chrome driver (webdriver_manager handles the download automatically)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

# Navigate to a URL
driver.get('https://quotes.toscrape.com/js/')

# Print the page title
print(f'Page title: {driver.title}')

# Close the browser
driver.quit()

When you run this, a Chrome window will pop up, navigate to the page, and print the title. The key difference: the browser actually runs the JavaScript, so the page is fully rendered.

Setting Up Your Selenium Workshop

This is the boring but necessary part — once it’s done, the fun begins. Let’s get everything installed.

First, install the packages:

pip install selenium webdriver-manager

webdriver-manager is a lifesaver. It automatically downloads the correct browser driver for your Chrome version and sets the PATH. Without it, you’d have to manually download ChromeDriver, match versions, and handle PATH errors.

Now, let’s set up Chrome in both normal and headless modes:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

# Normal (headful) mode — you'll see the browser window
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get('https://quotes.toscrape.com/js/')
print(f'Headful mode - Title: {driver.title}')
driver.quit()

# Headless mode — runs in the background, no visible window
chrome_options = Options()
chrome_options.add_argument('--headless')
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.get('https://quotes.toscrape.com/js/')
print(f'Headless mode - Title: {driver.title}')
driver.quit()

Headless mode is faster and doesn’t pop up windows, which is great for production. But when you’re debugging, use headful mode so you can see what’s happening.

Finding Your Way Around: Locating Elements

This is the hardest part of Selenium. How do you tell the robot which button to click or which text to grab?

Selenium needs a way to find elements on the page — like a GPS coordinate. You provide these coordinates using locators. The most common ones are:

  • ID: find_element(By.ID, 'quote') — fastest, but IDs must be unique
  • Class name: find_element(By.CLASS_NAME, 'quote') — works for multiple elements
  • CSS selector: find_element(By.CSS_SELECTOR, 'div.quote') — powerful and flexible
  • XPath: find_element(By.XPATH, '//div[@class="quote"]') — most powerful, but can be fragile

Here’s the catch: XPath is the most powerful locator, but it can break if the page structure changes. Always use relative XPaths (starting with //) rather than absolute ones (starting with /html/body/...).

Let’s see how to use them:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get('https://quotes.toscrape.com/js/')

# Wait a moment for JavaScript to load (we'll learn proper waiting next)
import time
time.sleep(2)

# Find the first quote using different locators
# Using class name
quote_by_class = driver.find_element(By.CLASS_NAME, 'quote')
print(f'By class name: {quote_by_class.text[:50]}...')

# Using CSS selector
quote_by_css = driver.find_element(By.CSS_SELECTOR, 'div.quote')
print(f'By CSS selector: {quote_by_css.text[:50]}...')

# Using XPath
quote_by_xpath = driver.find_element(By.XPATH, '//div[@class="quote"]')
print(f'By XPath: {quote_by_xpath.text[:50]}...')

# Find ALL quotes (plural)
all_quotes = driver.find_elements(By.CLASS_NAME, 'quote')
print(f'Total quotes on page: {len(all_quotes)}')

driver.quit()

Pro tip: Use your browser’s DevTools (right-click → Inspect) to test XPath/CSS selectors before writing code. In the console, you can type $x('//div[@class="quote"]') to test XPath or $$('div.quote') to test CSS selectors.

The Art of Waiting: Why Your Script Needs Patience

This is the hardest part of Selenium. You tell the robot to click a button, but the button hasn’t appeared yet — the page is still loading JavaScript. If you don’t wait, your script crashes with a NoSuchElementException.

There are two types of waits:

  1. Implicit wait: Tell Selenium to poll the DOM for a certain time before throwing an exception. Simple, but can be inefficient because it applies to every element lookup.

  2. Explicit wait: Wait for a specific condition (element visible, clickable, etc.) using WebDriverWait and expected_conditions. More precise and faster.

Here’s what happens without a wait:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get('https://quotes.toscrape.com/js/')

# No wait — this will likely fail because JavaScript hasn't loaded yet
try:
    quote = driver.find_element(By.CLASS_NAME, 'quote')
    print(f'Quote: {quote.text}')
except Exception as e:
    print(f'Error: {e}')

driver.quit()

Now, with an explicit wait:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get('https://quotes.toscrape.com/js/')

# Explicit wait: wait up to 10 seconds for the quote element to be present
wait = WebDriverWait(driver, 10)
quote = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'quote')))

print(f'Quote found: {quote.text[:50]}...')

driver.quit()

The explicit wait polls the DOM every 500 milliseconds (by default) until the element appears or the timeout is reached. This is much more reliable than a fixed time.sleep() because it adapts to network speed.

Common conditions you’ll use:

  • presence_of_element_located — element exists in DOM
  • visibility_of_element_located — element is visible on screen
  • element_to_be_clickable — element is visible and enabled

Interacting with the Page: Click, Scroll, Type

Now that you can find elements and wait for them, it’s time to make the robot do things. Scrolling down to load more items, clicking a ‘Load More’ button, filling a search form — these are the actions that unlock dynamic data.

Let’s build a script that scrolls through an infinite-scroll page and clicks a ‘Load More’ button:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get('https://quotes.toscrape.com/js/')

wait = WebDriverWait(driver, 10)

# Wait for quotes to load initially
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'quote')))

# Scroll to the bottom to trigger lazy loading (if applicable)
# This simulates pressing Page Down
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
time.sleep(2)  # Give time for new content to load

# Find and click the 'Next' button (pagination)
# Note: quotes.toscrape.com/js has a 'Next' button at the bottom
try:
    next_button = driver.find_element(By.CSS_SELECTOR, 'li.next a')
    # Wait until it's clickable
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'li.next a')))
    next_button.click()
    print('Clicked Next button')
    
    # Wait for new quotes to load
    wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'quote')))
    
    # Count quotes on the new page
    quotes = driver.find_elements(By.CLASS_NAME, 'quote')
    print(f'Quotes on page 2: {len(quotes)}')
except Exception as e:
    print(f'Could not find Next button: {e}')

driver.quit()

For typing into forms, use send_keys():

search_box = driver.find_element(By.NAME, 'search')
search_box.clear()  # Clear any existing text
search_box.send_keys('data science')
search_box.submit()  # Submit the form

For dropdowns, use the Select class:

from selenium.webdriver.support.ui import Select

dropdown = Select(driver.find_element(By.ID, 'sort'))
dropdown.select_by_visible_text('Price: Low to High')

Extracting the Data: Selenium’s Built-In Methods vs. BeautifulSoup

You have the page loaded with all the dynamic content. Now how do you get the data out?

Selenium can give you the text and attributes directly, but sometimes it’s easier to pass the page source to BeautifulSoup for cleaner parsing. Let’s compare both approaches:

Approach 1: Selenium alone

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get('https://quotes.toscrape.com/js/')

wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'quote')))

# Extract using Selenium's built-in methods
quotes = driver.find_elements(By.CLASS_NAME, 'quote')
for quote in quotes[:3]:  # First 3 quotes
    text = quote.find_element(By.CLASS_NAME, 'text').text
    author = quote.find_element(By.CLASS_NAME, 'author').text
    tags = [tag.text for tag in quote.find_elements(By.CLASS_NAME, 'tag')]
    print(f'"{text}" — {author}')
    print(f'Tags: {tags}')
    print('---')

driver.quit()

Approach 2: Selenium + BeautifulSoup

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get('https://quotes.toscrape.com/js/')

wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'quote')))

# Get the fully rendered HTML
page_source = driver.page_source

# Feed it to BeautifulSoup
soup = BeautifulSoup(page_source, 'html.parser')
quotes = soup.find_all('div', class_='quote')

for quote in quotes[:3]:
    text = quote.find('span', class_='text').text
    author = quote.find('small', class_='author').text
    tags = [tag.text for tag in quote.find_all('a', class_='tag')]
    print(f'"{text}" — {author}')
    print(f'Tags: {tags}')
    print('---')

driver.quit()

Both approaches work. The Selenium+BeautifulSoup approach is often faster for parsing large HTML because BeautifulSoup’s find_all is more efficient than Selenium’s find_elements for many elements. But for simple extractions, Selenium alone is fine.

Handling the Tricky Stuff: Headless Mode, CAPTCHAs, and Anti-Scraping

Real-world scraping isn’t always smooth. Sites don’t like being scraped — they throw CAPTCHAs, block your IP, or detect Selenium. Here’s how to handle the most common obstacles.

First, let’s build a script that uses anti-detection techniques:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import random

# Set up Chrome options for stealth
chrome_options = Options()
chrome_options.add_argument('--headless')  # Run in background
chrome_options.add_argument('--disable-blink-features=AutomationControlled')  # Hide automation
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

# Set a custom user-agent to look like a real browser
chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)

driver.get('https://quotes.toscrape.com/js/')

wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'quote')))

# Add random delays to mimic human behavior
time.sleep(random.uniform(1, 3))

quotes = driver.find_elements(By.CLASS_NAME, 'quote')
print(f'Found {len(quotes)} quotes')

# Add another random delay before quitting
time.sleep(random.uniform(0.5, 1.5))
driver.quit()

For CAPTCHAs: Selenium can’t solve them automatically. You have three options:

  1. Use a CAPTCHA-solving service like 2Captcha
  2. Handle them manually (pause the script and solve it yourself)
  3. Avoid sites that use aggressive CAPTCHAs

For session management, you can save and load cookies:

import pickle

# Save cookies after logging in
cookies = driver.get_cookies()
with open('cookies.pkl', 'wb') as f:
    pickle.dump(cookies, f)

# Load cookies in a new session
with open('cookies.pkl', 'rb') as f:
    cookies = pickle.load(f)
for cookie in cookies:
    driver.add_cookie(cookie)

Ethical reminder: Always respect robots.txt, rate-limit your requests (add delays), and don’t overload servers. Scraping is a tool, not a weapon.

Putting It All Together: A Complete Scraping Script

Now we build a full, production-ready script that scrapes a dynamic site from start to finish. We’ll scrape all quotes from quotes.toscrape.com/js with pagination.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import csv
import time
import random

# --- Setup ---
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
wait = WebDriverWait(driver, 10)

# --- Navigate to first page ---
driver.get('https://quotes.toscrape.com/js/')

# --- Prepare CSV file ---
with open('quotes.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerow(['quote', 'author', 'tags'])
    
    page_num = 1
    while True:
        print(f'Scraping page {page_num}...')
        
        # Wait for quotes to load
        wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'quote')))
        
        # Add random delay to be polite
        time.sleep(random.uniform(1, 2))
        
        # Extract quotes from current page
        quotes = driver.find_elements(By.CLASS_NAME, 'quote')
        for quote in quotes:
            text = quote.find_element(By.CLASS_NAME, 'text').text
            author = quote.find_element(By.CLASS_NAME, 'author').text
            tags = ', '.join([tag.text for tag in quote.find_elements(By.CLASS_NAME, 'tag')])
            writer.writerow([text, author, tags])
        
        print(f'  Found {len(quotes)} quotes on page {page_num}')
        
        # Try to find and click the 'Next' button
        try:
            next_button = driver.find_element(By.CSS_SELECTOR, 'li.next a')
            if next_button.is_enabled():
                wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'li.next a')))
                next_button.click()
                page_num += 1
            else:
                print('Next button disabled, stopping.')
                break
        except:
            print('No more pages. Scraping complete.')
            break

print(f'Scraped {page_num} pages total.')
driver.quit()

# --- Show a preview ---
import pandas as pd
df = pd.read_csv('quotes.csv')
print(df.head())
print(f'\nTotal quotes scraped: {len(df)}')

This script:

  1. Sets up Chrome in headless mode with anti-detection
  2. Navigates to the first page
  3. Waits for quotes to load
  4. Extracts quote text, author, and tags
  5. Clicks the ‘Next’ button until no more pages exist
  6. Saves everything to a CSV file
  7. Shows a preview of the data

Conclusion: You’ve Unlocked the Dynamic Web

You can now scrape sites that were previously out of reach. Let’s recap what you’ve learned:

  • Selenium controls a real browser — it runs JavaScript, so you can access content that BeautifulSoup can’t see
  • Waiting is essential — explicit waits with WebDriverWait are your best friend for dynamic content
  • Locators are your GPS — use IDs, CSS selectors, or XPath to find elements
  • Interaction unlocks data — clicking ‘Load More’, scrolling, and filling forms reveals hidden content
  • Combine tools — use Selenium to load the page, then BeautifulSoup to parse it for cleaner code

Compared to other tools: Selenium is slower but more capable than requests + BeautifulSoup. Scrapy can be combined with Selenium via middleware for large-scale scraping.

Next steps: Explore headless browsers like Playwright or Puppeteer for comparison. Learn about Scrapy-Selenium integration for production pipelines.

Ethical reminder: With great power comes great responsibility. Always respect robots.txt, rate-limit your requests, and don’t overload servers. Scrape ethically.

Check Your Understanding

Remember: What is the main difference between Selenium and BeautifulSoup?

Understand: Why do you need explicit waits when scraping dynamic sites?

Apply: Given a page with a ‘Load More’ button that reveals 10 new items each click, write pseudocode for scraping all items.

Analyze: A script that uses implicit wait of 10 seconds still fails sometimes — what could be wrong?

Evaluate: Compare using Selenium alone vs Selenium+BeautifulSoup for a page with 5000 elements — which is faster and why?

Create: Design a scraping strategy for a single-page app that loads data via API calls (no traditional pagination).

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • Python Engineering Under review

    Python String Formatting Reference Format And F St

    print("Hello, %s! Your number is %d." % (name, value)) print("Hello, {}! Your number is {}.".format(name, value)) print(f"Hello, {name}! Your number is {value}.")

  • Python Engineering Under review

    Web Scraping For Data Science Beautifulsoup Vs Scr

    Let's get the definition straight first. Web scraping is the process of fetching a web page and extracting specific pieces of information from it. That's it. Two steps: fetch, then extract.

  • Python Engineering Under review

    Stop Making Variable Soup: A Guide to Pandas Method Chaining

    Replace messy intermediate dataframes with clean Pandas method chains using .assign(), .pipe(), and .query() to build readable, maintainable data pipelines.

  • Python Engineering Under review

    Sending Automated Emails And Reports From A Python

    You just spent three hours building a beautiful pandas report. You cleaned the data, created a summary table, made a chart, and exported everything to a CSV file.

Looking for something else?

Search every article by title, summary or topic.