Selenium is a browser automation framework with bindings for several languages, including Python. Your script drives a real browser: it opens pages, clicks links, fills in forms and reads what appears on screen, much like a human user would.
Libraries like Requests and Beautiful Soup only fetch and parse HTML. Selenium runs an actual browser, so it can handle pages that depend on JavaScript, pop-ups, iframes and other interactions. The trade-off is speed: launching a browser is slower and heavier, and it is harder to run quietly in the background if all you need is to download a few files.
Practice site
All the examples below use the-internet.herokuapp.com. It is a great place to test edge cases like JavaScript alerts, iframes, dynamic loading, hovers and file uploads, and it shows clearly why waits and stable element locators matter.
1. How Selenium actually works
Selenium is not a single program. It is a set of tools built around a communication protocol called WebDriver.
The architecture:
- Python script: sends commands like "click the button with ID 'submit'".
- The driver (ChromeDriver for Chrome, geckodriver for Firefox): a separate background program that sits between your code and the browser. It listens on a local network port.
- The browser: receives the command from the driver and performs the action for real.
The catch: every action travels the whole chain. Python talks to the driver, the driver talks to the browser, the browser renders the page and the result comes back the same way. That round trip is a big part of why Selenium feels slow.
The lifecycle: open, do, close
Every script follows three steps:
- Open the browser.
- Do stuff.
- Close the browser.
Always close the browser in a finally block. If your script crashes or is killed before it reaches quit(), browser and driver processes can be left running in the background, and repeated runs will slowly eat your RAM.
2. Starting a Selenium-controlled browser
Install Selenium inside your virtual environment:
pip install selenium from selenium import webdriver # 1. Open the browser (this is the "driver" object) driver = webdriver.Chrome() try: # 2. Do stuff driver.get("https://the-internet.herokuapp.com") finally: # 3. Close the browser, even if something above failed driver.quit() You need the browser itself installed. For the code above, that means Chrome.
Keeping the browser open
from selenium import webdriver browser = webdriver.Firefox() browser.get("https://the-internet.herokuapp.com") Running this opens Firefox and loads the page, but the window closes almost immediately. When the script ends, Python cleans up its objects, including the driver, and shutting the driver down closes the browser. Nothing told the script to wait.
Two ways to keep the window open so you can look at the page:
- Option A (the Python way): add
input("Press Enter to close...")at the end of your script. This pauses Python and keeps the driver alive. - Option B (the Selenium way, Chrome only): pass the
detachoption so Chrome stays open after the script finishes.
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_experimental_option("detach", True) driver = webdriver.Chrome(options=options) This option is specific to Chrome and does not work with Firefox.
A small practice project
import sys 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 from selenium.common.exceptions import WebDriverException url = "https://the-internet.herokuapp.com/login" # Catch driver start-up errors at the top level: they come from outside our code try: my_driver = webdriver.Firefox() except WebDriverException as e: print(f"Error: {e}") sys.exit(1) try: my_driver.get(url) # Fill in the username user_box = my_driver.find_element(By.ID, "username") user_box.send_keys("tomsmith") # Fill in the password pass_box = my_driver.find_element(By.ID, "password") pass_box.send_keys("SuperSecretPassword!") # Find the button and click it submit_bt = my_driver.find_element(By.CSS_SELECTOR, "button[type=submit]") submit_bt.click() # Wait for the success banner: # <div id="flash" class="flash success">You logged into a secure area!</div> success_banner = WebDriverWait(my_driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "div.flash.success")) ) print("Login successful:", success_banner.text) input("Press Enter to continue") except WebDriverException as e: print(f"Error occurred\nDetails: {e}") finally: my_driver.quit() Note that the banner is located with a CSS selector (div.flash.success). Selecting an element with several classes is cleaner this way than with By.CLASS_NAME.
3. Explicit waits
Pages built with JavaScript add elements to the page after the initial load. driver.get() only waits for the page's load event, not for background requests or re-renders. Your script can ask for an element a few milliseconds after it is created, so the element can be on screen when you look but missing when the script looks.
Running this script crashes with a NoSuchElementException:
from selenium import webdriver from selenium.webdriver.common.by import By url = "https://the-internet.herokuapp.com/dynamic_loading/2" my_driver = webdriver.Firefox() try: my_driver.get(url) start_bt = my_driver.find_element(By.CSS_SELECTOR, "div#start button") start_bt.click() # Too early: the finish text has not been rendered yet finish_elem = my_driver.find_element(By.CSS_SELECTOR, "div#finish h4") print(finish_elem.text) finally: my_driver.quit() The finish element takes a few seconds to appear, and the script asks for it immediately.
The fix is an explicit wait. It polls a condition until it is true or a timeout runs out:
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 url = "https://the-internet.herokuapp.com/dynamic_loading/2" my_driver = webdriver.Firefox() try: my_driver.get(url) my_driver.find_element(By.CSS_SELECTOR, "div#start button").click() finish_elem = WebDriverWait(my_driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "div#finish h4")) ) print(finish_elem.text) finally: my_driver.quit() A few details worth knowing:
-
until()returns the result of the condition, usually the element itself. If the time runs out, it raises aTimeoutException. - Pick the condition that matches what you need.
presence_of_element_locatedonly checks that the element is in the DOM,visibility_of_element_locatedchecks that it can be seen, andelement_to_be_clickablechecks that it can be clicked. - Selenium also has an implicit wait (
driver.implicitly_wait(10)), which makes everyfind_elementcall retry for up to that long. Do not mix it with explicit waits: an explicit wait works by callingfind_elementrepeatedly, so the two timeouts stack and your waiting times become unpredictable. Explicit waits are the better habit, and the one this handbook uses.
4. Working with iframes
An iframe is an HTML document embedded inside another HTML document. A common real-world example is a payment form from Stripe or PayPal embedded on a checkout page.
Selenium cannot see inside an iframe by default, because the browser keeps it as a separate, isolated document.
The solution: switch Selenium's context into the iframe, do your work, then switch back.
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 from selenium.common.exceptions import WebDriverException my_driver = webdriver.Firefox() url = "https://the-internet.herokuapp.com/iframe" try: my_driver.get(url) wait = WebDriverWait(my_driver, 10) # Switch as soon as the frame is available wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "mce_0_ifr"))) text_box = my_driver.find_element(By.ID, "tinymce") text_box.clear() text_box.send_keys("Hello from Selenium") # Switch back to the main page: a critical step my_driver.switch_to.default_content() input("...") except WebDriverException as err: print(f"Some error occurred: {err}") finally: my_driver.quit() Working with iframes follows three steps:
- Switch to the iframe.
- Work with the content inside it.
- Exit the frame before interacting with the main page.
For nested frames (an iframe inside another iframe), use my_driver.switch_to.parent_frame() to move up one level. default_content() always jumps straight back to the main page.
5. Handling JavaScript alerts
Sooner or later you will meet JavaScript alerts: native browser pop-ups that block the page until someone responds to them.
Why find_element fails
Alerts are not part of the HTML DOM. They come from the browser itself, so you cannot inspect them in DevTools or locate them with CSS selectors or XPath. While an alert is open, the page cannot be interacted with, and trying to touch a normal element raises an UnexpectedAlertPresentException.
The solution: driver.switch_to.alert
This shifts Selenium's focus from the HTML document to the browser's native pop-up. There are three types:
- Alert: a message with an OK button.
- Confirm: a message with OK and Cancel buttons.
- Prompt: a message with a text field plus OK and Cancel.
The standard workflow
Follow this order: Wait → Switch → Read/Type → Accept/Dismiss.
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 1. Trigger the alert driver.find_element(By.XPATH, "//button[text()='Click for JS Prompt']").click() # 2. Wait for the alert to appear (prevents race conditions) WebDriverWait(driver, 10).until(EC.alert_is_present()) # 3. Switch focus to the alert alert = driver.switch_to.alert # 4. Interact with it print(f"Alert says: {alert.text}") # Only prompt alerts accept text. Calling send_keys on a plain alert raises an error. alert.send_keys("My automated response") # 5. Resolve it (this unblocks the page) alert.accept() # clicks OK # alert.dismiss() # clicks Cancel 6. Hover menus and hover actions
Many sites hide content until the mouse hovers over something. If you try find_element().click() on a hidden element, Selenium raises an "element not interactable" error. To get at it, simulate the hover first using Action Chains.
Take the hovers page, where text is hidden behind each avatar:
Case 1: find the hidden link and click it directly.
my_driver.find_element(By.CSS_SELECTOR, ".figcaption a").click() # Raises an "element not interactable" error: the link is hidden until a hover Case 2: use Action Chains to hover first, then read the text.
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 from selenium.webdriver.common.action_chains import ActionChains url = "https://the-internet.herokuapp.com/hovers" my_driver = webdriver.Firefox() wait = WebDriverWait(my_driver, 10) try: my_driver.get(url) avatar = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".figure"))) # Hover over the avatar action = ActionChains(my_driver) action.move_to_element(avatar).perform() hidden_text = wait.until( EC.visibility_of_element_located((By.CSS_SELECTOR, ".figcaption h5")) ) print(hidden_text.text) input("...") finally: my_driver.quit() 7. Handling file uploads
The golden rule: never click the operating system's "Browse" button. Once the native file picker opens, Selenium loses control and the script freezes until a human closes it. Instead, locate the <input type="file"> element and send the absolute file path straight to it with send_keys().
file_path = "/absolute/path/to/sample.txt" driver.find_element(By.ID, "file-upload").send_keys(file_path) The page receives the file as if a user had picked it. You can then click the submit button normally.
8. Configuring downloads (the silent save)
Clicking a download button usually opens an OS-level save dialog, which Selenium cannot control. The fix is to configure Firefox before launching it, so it saves files to a chosen folder without asking.
from selenium import webdriver from selenium.webdriver.firefox.options import Options options = Options() options.set_preference("browser.download.folderList", 2) options.set_preference("browser.download.dir", "/absolute/path/to/downloads") options.set_preference( "browser.helperApps.neverAsk.saveToDisk", "application/pdf,text/plain,application/json", ) driver = webdriver.Firefox(options=options) folderList set to 2 means "use the custom folder given in browser.download.dir". The neverAsk.saveToDisk preference lists the file types (MIME types) Firefox should save automatically instead of showing a pop-up, so list every type you expect. This is the silent save: configure the browser, click the download through Selenium, and let Firefox handle the file in the background.
Conclusion
Selenium is tough at first, but it unlocks dynamic web automation that tools limited to plain HTTP requests cannot easily handle. My practice scripts covered the browser lifecycle, explicit waits, iframes, alerts, hovers, file uploads and silent downloads. They are on my GitHub profile at github.com/4kit1-glitch.
To finish, I built a capstone project. To avoid touching any real website, I used a custom-built, simple two-page Django site (generated with Copilot) as the test target, and wrote the Selenium script myself. It fills in a form, waits for processing, reads the results from the screen and downloads them as JSON. It runs so fast that a screen recording barely shows anything, so the code is the best demo: https://github.com/4kit1-glitch/flexSelenium
Playwright is next on my list. From what I have read, it has a cleaner API, built-in auto-waiting, network interception and tracing. I have not tried it yet, so I will compare it with Selenium properly once I have. Either way, the concepts you learn here (DOM context, waits, actions and browser configuration) carry over directly to tools like Playwright. If you found this helpful or have any questions you can leave a comment