πŸ”¨ LearnForge

Selenium Python Tutorial 2026: Complete Web Automation Guide

Master web automation with Selenium and Python. Learn browser testing, web scraping, and automated interactions with practical, real-world examples.

πŸ“… Updated January 7, 2026 ⏱️ 15 min read ✍️ LearnForge Team
Selenium Python Web Automation Tutorial

What is Selenium Python?

Selenium is an open-source framework that automates web browsers. When combined with Python, it becomes a powerful tool for web testing, automation, and scraping. Selenium Python allows you to programmatically control browsers like Chrome, Firefox, Safari, and Edgeβ€”clicking buttons, filling forms, navigating pages, and extracting data exactly as a human would.

Originally developed for automated testing, Selenium has evolved into a versatile automation tool used by developers, QA engineers, data scientists, and automation specialists worldwide.

πŸ’‘ Real-world use case: A QA team in Vancouver automated their regression testing suite with Selenium Python, reducing testing time from 40 hours to 2 hours per release cycle.

Installation and Setup

Step 1: Install Python

Ensure Python 3.8 or newer is installed. Check your version:

python --version

Step 2: Install Selenium

Install Selenium using pip:

pip install selenium

Step 3: Install WebDriver

From Selenium 4.6+, WebDriver Manager is built-in. However, you can also install it manually:

pip install webdriver-manager

Browser Options:

  • Chrome: Most popular choice. Fast and reliable.
  • Firefox: Great for privacy-focused automation.
  • Edge: Good for Windows environments.
  • Safari: For macOS testing (requires additional setup).

Your First Selenium Script

Let's write a simple script that opens Google, searches for "Python Automation", and prints the page title:

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

# Setup Chrome WebDriver
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

try:
    # Navigate to Google
    driver.get("https://www.google.com")

    # Find search box and enter query
    search_box = driver.find_element(By.NAME, "q")
    search_box.send_keys("Python Automation")
    search_box.send_keys(Keys.RETURN)

    # Wait for results to load
    time.sleep(2)

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

finally:
    # Close browser
    driver.quit()

Save this as first_selenium.py and run it. You'll see Chrome open automatically, perform the search, and close!

⚠️ Note: Always use driver.quit() in a finally block to ensure the browser closes even if an error occurs.

Locating Web Elements

Finding elements on a page is fundamental to Selenium. Here are the most common locator strategies:

By ID

The most reliable method. IDs should be unique on the page.

element = driver.find_element(By.ID, "username")

By Class Name

Find elements by CSS class.

element = driver.find_element(By.CLASS_NAME, "btn-primary")

By CSS Selector

Powerful and flexible. Use CSS selectors like in stylesheets.

element = driver.find_element(By.CSS_SELECTOR, "input[type='email']")

By XPath

Very powerful but can be complex. Navigate the DOM structure.

element = driver.find_element(By.XPATH, "//button[@class='submit']")

By Link Text

Find links by their visible text.

element = driver.find_element(By.LINK_TEXT, "Sign up")

Browser Interactions

Clicking Elements

button = driver.find_element(By.ID, "submit-btn")
button.click()

Filling Forms

# Enter text
input_field = driver.find_element(By.NAME, "email")
input_field.send_keys("user@example.com")

# Clear existing text
input_field.clear()

# Submit form
input_field.submit()

Dropdown Selection

from selenium.webdriver.support.ui import Select

dropdown = Select(driver.find_element(By.ID, "country"))
dropdown.select_by_visible_text("Canada")
# Or: dropdown.select_by_value("ca")
# Or: dropdown.select_by_index(1)

Handling Alerts

# Accept alert
alert = driver.switch_to.alert
alert.accept()

# Dismiss alert
alert.dismiss()

# Get alert text
alert_text = alert.text

Taking Screenshots

driver.save_screenshot("screenshot.png")

Waits and Synchronization

Modern websites load dynamically. Proper waiting strategies are crucial for reliable automation.

❌ Implicit Wait (Not Recommended for Complex Apps)

Sets a default wait time for all element searches. Simple but less flexible.

driver.implicitly_wait(10)  # Wait up to 10 seconds

βœ… Explicit Wait (Recommended)

Wait for specific conditions. More reliable and precise.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Wait for element to be clickable
element = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.ID, "submit-button"))
)
element.click()

# Wait for element to be visible
element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.CLASS_NAME, "result"))
)

πŸ’‘ Pro Tip: Use explicit waits instead of time.sleep(). They're faster and more reliable because they proceed as soon as the condition is met.

Practical Examples

Example 1: Automated Login

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()

try:
    # Navigate to login page
    driver.get("https://example.com/login")

    # Wait for and fill username
    username = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "username"))
    )
    username.send_keys("your_username")

    # Fill password
    password = driver.find_element(By.ID, "password")
    password.send_keys("your_password")

    # Click login button
    login_button = driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
    login_button.click()

    # Wait for dashboard to load
    WebDriverWait(driver, 10).until(
        EC.url_contains("/dashboard")
    )

    print("Login successful!")

finally:
    driver.quit()

Example 2: Web Scraping E-commerce Products

from selenium import webdriver
from selenium.webdriver.common.by import By
import pandas as pd

driver = webdriver.Chrome()

try:
    driver.get("https://example-shop.com/products")

    # Wait for products to load
    driver.implicitly_wait(5)

    # Find all product cards
    products = driver.find_elements(By.CLASS_NAME, "product-card")

    data = []
    for product in products:
        name = product.find_element(By.CLASS_NAME, "product-name").text
        price = product.find_element(By.CLASS_NAME, "product-price").text
        rating = product.find_element(By.CLASS_NAME, "rating").text

        data.append({
            'Name': name,
            'Price': price,
            'Rating': rating
        })

    # Save to CSV
    df = pd.DataFrame(data)
    df.to_csv('products.csv', index=False)
    print(f"Scraped {len(data)} products!")

finally:
    driver.quit()

Example 3: Automated Form Filling

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome()

try:
    driver.get("https://example.com/application-form")

    # Fill text fields
    driver.find_element(By.NAME, "first_name").send_keys("John")
    driver.find_element(By.NAME, "last_name").send_keys("Doe")
    driver.find_element(By.NAME, "email").send_keys("john@example.com")

    # Select from dropdown
    country = Select(driver.find_element(By.ID, "country"))
    country.select_by_visible_text("Canada")

    # Select radio button
    driver.find_element(By.ID, "experience-5years").click()

    # Check checkbox
    driver.find_element(By.ID, "terms-agree").click()

    # Submit form
    driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()

    print("Form submitted successfully!")

finally:
    driver.quit()

πŸŽ“ Master Selenium automation: Our Python Automation Course includes comprehensive Selenium modules with real-world projects, covering everything from basics to advanced techniques.

Selenium Python in Canada

Canadian tech companies and professionals extensively use Selenium Python for various automation needs:

πŸ™οΈ Toronto - Financial Services

Toronto's banking sector uses Selenium for automated testing of online banking platforms, ensuring security and reliability. QA teams automate regression testing across multiple browsers and devices.

🌊 Vancouver - E-commerce

Vancouver's e-commerce companies use Selenium for price monitoring, inventory tracking, and competitive analysis. Automated scripts monitor product availability and price changes 24/7.

🍁 Montreal - Media & Entertainment

Montreal's gaming and media companies leverage Selenium for automated UI testing of web-based games and streaming platforms. Cross-browser compatibility testing is crucial for their global audiences.

πŸ›’οΈ Calgary - Energy Sector

Calgary's energy companies use Selenium to automate data extraction from web portals, regulatory compliance reporting, and monitoring of energy market platforms.

πŸ›οΈ Ottawa - Government & Tech

Ottawa's tech sector and government contractors use Selenium for automated testing of public-facing web services, ensuring accessibility and functionality across platforms.

Best Practices

🎯 Use Explicit Waits

Avoid time.sleep(). Use WebDriverWait with expected conditions for reliable, fast automation.

πŸ” Prefer CSS Selectors over XPath

CSS selectors are faster and more readable. Use XPath only when CSS selectors can't achieve what you need.

🧹 Close Browsers Properly

Always use driver.quit() in a finally block to prevent memory leaks and zombie browser processes.

πŸ”„ Handle Exceptions

Wrap your code in try-except blocks to handle NoSuchElementException, TimeoutException, and other common errors gracefully.

🎭 Use Headless Mode for Production

Run browsers in headless mode for faster execution and server environments.

from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)

πŸ“Έ Take Screenshots on Failures

Capture screenshots when tests fail to help debug issues quickly.

Frequently Asked Questions

What is Selenium Python?

Selenium Python is a combination of the Selenium WebDriver automation framework with Python programming language. It allows you to automate web browsers, test websites, scrape data, and perform automated tasks on web applications.

Is Selenium with Python easy to learn?

Yes, Selenium with Python is beginner-friendly. Python's simple syntax combined with Selenium's intuitive API makes it easy to learn. Most beginners can write their first automation script within a few hours with proper guidance.

What can you automate with Selenium Python?

You can automate web testing, form submissions, data scraping, login processes, navigation, clicking buttons, filling forms, taking screenshots, handling alerts, and virtually any browser interaction that a human can perform.

Is Selenium Python good for web scraping?

Yes, Selenium is excellent for scraping dynamic websites that use JavaScript. It can handle AJAX requests, wait for elements to load, and interact with modern web applications that traditional scrapers cannot handle.

Which browser is best for Selenium Python?

Chrome with ChromeDriver is most popular due to speed and reliability. Firefox with GeckoDriver is also excellent. Both work well with Selenium Python, and the choice depends on your specific needs and testing requirements.

Ready to Master Python Automation?

Join thousands of students learning Python automation with practical, hands-on training.

Start Learning Now - $99 CAD

Related Articles

Python Automation Guide

Complete guide to Python automation. Learn file automation, web scraping, and more.