Concept Explanation
Some modern websites (like Gmail, Twitter, or complex dashboards) are "Dynamic." When you download their HTML with requests, the page is empty because the content is loaded later by JavaScript. BeautifulSoup cannot see this content.
Selenium is different. It doesn't just download a file; it actually opens a real web browser (Chrome, Firefox, or Edge) on your computer. It can click buttons, type into search bars, scroll down the page, and wait for JavaScript to load. If it can be done by a human in a browser, it can be done by Selenium.
Syntax or Core Structure
Setting up the Driver
You need the selenium library and a "WebDriver" that matches your browser.
from selenium import webdriver
from selenium.webdriver.common.by import By
# 1. Initialize the browser
driver = webdriver.Chrome()
# 2. Go to a URL
driver.get("https://www.google.com")
# 3. Find an element
search_box = driver.find_element(By.NAME, "q")
# 4. Interact!
search_box.send_keys("Python Automation")
search_box.submit()
# 5. Close!
# driver.quit()
Code Example #1 (Basic)
Waiting for elements to appear (Explicit Waits).
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Wait up to 10 seconds for the 'Login' button to be clickable
wait = WebDriverWait(driver, 10)
login_btn = wait.until(EC.element_to_be_clickable((By.ID, "login-submit")))
login_btn.click()
Code Example #2 (Intermediate)
Handling "infinite scroll" pages.
import time
# Scroll to the bottom of the page 5 times
for i in range(5):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2) # Wait for new content to load
Real World Example
Automated Login: Logging into a dummy portal and taking a screenshot.
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://the-internet.herokuapp.com/login")
# Type credentials
driver.find_element(By.ID, "username").send_keys("tomsmith")
driver.find_element(By.ID, "password").send_keys("SuperSecretPassword!")
# Click Login
driver.find_element(By.CSS_SELECTOR, "button.radius").click()
# Take a screenshot to prove it worked
driver.save_screenshot("dashboard.png")
driver.quit()
Common Mistakes
- Driver Version Mismatch: Your Chrome Updates, but your
chromedriver.exeis old. Selenium will crash. Use thewebdriver-managerlibrary to fix this automatically. - Not Waiting: Selenium is faster than your Wi-Fi. If you try to click a button before the page loads, you'll get a
NoSuchElementException. Always use Waits. - Leaving Browsers Open: If your script crashes, the Chrome window stays open, eating your RAM. Use
try...finally: driver.quit().
Best Practices
- Headless Mode: Run the browser in the background (
options.add_argument("--headless")) so it doesn't pop up and interrupt your work. - Select by ID: Just like scraping, IDs are the most stable way to find elements.
- Don't Hardcode Sleeps: Avoid
time.sleep(5). It's lazy. UseWebDriverWaitso your script finishes as soon as the element is ready.
Practice Exercises
- The Searcher: Write a script that opens Google, searches for "CodeAcademix," and prints the title of the first result.
- The Screenshotter: Visit a website that requires scrolling (like a news feed) and take a screenshot of the very bottom of the page.
- The Form Filler: Find a simple contact form online and write a script to fill out the Name, Email, and Message fields (but don't click submit!).