Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To automate a browser with Python, install Selenium, open a supported browser through WebDriver, navigate to a page, locate and interact with elements, wait for the page to respond, then close the session with driver.quit(). For most current Selenium installations, Selenium Manager handles browser-driver setup automatically; you still need the browser installed.

What you need before you start

  • Python installed and available as python or python3 in your terminal.
  • Selenium’s Python package, installed in the environment where you will run the script.
  • A supported browser, such as Chrome. Selenium Manager usually obtains and manages the corresponding driver for current Selenium versions.

Older Selenium versions, restricted networks, or unusual browser installations may require explicit driver configuration. Check the official Selenium Manager documentation if automatic setup fails.

Install Selenium in an isolated environment

A virtual environment keeps this project’s Python packages separate from other projects. Selenium’s Python API documentation recommends considering one for an isolated installation.

  1. Create a project directory and enter it: mkdir selenium-demo, then cd selenium-demo.
  2. Create a virtual environment: on macOS or Linux, run python3 -m venv .venv; on Windows, run py -m venv .venv.
  3. Activate it: macOS/Linux: source .venv/bin/activate; Windows Command Prompt: .venvScriptsactivate; Windows PowerShell: .venvScriptsActivate.ps1.
  4. Install Selenium: run python -m pip install selenium.
  5. Optionally record a pinned dependency: run python -m pip freeze > requirements.txt. Selenium’s installation guide uses selenium==4.49.0 as an example pin; that example is not a promise that this will be the latest version when you install.

For another setup option or the latest installation guidance, see the official Selenium Python installation guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Run a first browser automation script

The example below opens Selenium’s demonstration form, enters text, submits it, reads the result, and closes the browser even if an error occurs. Save it as first_script.py.

from selenium import webdriver
from selenium.webdriver.common.by import By

# Selenium Manager generally handles driver setup with current Selenium versions.
driver = webdriver.Chrome()
try:
    driver.get("https://www.selenium.dev/selenium/web/web-form.html")
    print("Page title:", driver.title)

    text_box = driver.find_element(by=By.NAME, value="my-text")
    submit_button = driver.find_element(by=By.CSS_SELECTOR, value="button")

    text_box.send_keys("Selenium")
    submit_button.click()

    message = driver.find_element(by=By.ID, value="message")
    print("Result:", message.text)
finally:
    driver.quit()

Run it from the activated environment with python first_script.py. The script should open a browser, submit the form, print the page title and resulting message, then close the browser. This follows the sequence in Selenium’s official first Selenium script; the code has not been independently run for this article.

Understand the WebDriver interaction cycle

Start a session and navigate

webdriver.Chrome() starts a WebDriver session for Chrome. driver.get(url) navigates that browser to a page and waits for the page’s load condition, but JavaScript-driven content may still appear later.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Find elements with locators

driver.find_element(by=..., value=...) returns a matching element. The example uses three locator strategies:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • By.NAME finds the text field by its HTML name attribute.
  • By.CSS_SELECTOR finds a button using a CSS selector.
  • By.ID finds the result element by its HTML id.

If a locator matches nothing, Selenium raises an exception rather than returning an empty element. Use a stable attribute when possible, and confirm the element is actually present on the page before relying on its locator.

Interact and inspect results

Use send_keys() to type into a field and click() to activate a control. Read visible text with an element’s .text property. For automated checks, compare the result with the expected value and raise an assertion or report a test failure if it does not match.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Close the session

driver.quit() ends the WebDriver session and closes the browser by default. Putting it in a finally block ensures cleanup even when navigation, locating, or interaction raises an error.

Wait for dynamic pages instead of guessing

A page may load its controls or results asynchronously. Selenium’s documentation identifies synchronizing with the current browser state as one of the biggest challenges in Selenium automation. A fixed sleep can be too short on a slow response and waste time on a fast one.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The first-script guide demonstrates an implicit wait as a simple example but says it is rarely the best solution. For real scripts, use an explicit wait for the condition you need, such as an element becoming visible or clickable. See the official waiting strategies guide for the supported approaches and their behavior. Avoid casually mixing implicit and explicit waits, because their combined timing can be difficult to reason about.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Common setup and runtime problems

Symptom Likely cause What to try
Python reports No module named 'selenium'. Selenium was installed into a different Python environment, or the virtual environment is not active. Activate .venv, then run python -m pip install selenium using the same python command that runs the script.
WebDriver cannot start the browser or reports a driver problem. The browser is missing, Selenium is old, the browser installation is unusual, or the environment prevents Selenium Manager from resolving a driver. Install a supported browser and update Selenium. If automatic setup remains unavailable, follow Selenium Manager’s guidance for your browser and environment.
NoSuchElementException appears. The locator is wrong, the element has not appeared yet, or the page has not reached the expected state. Verify the element’s attributes and locator, then wait for the relevant element or state rather than assuming navigation means all dynamic content is ready.
The script is inconsistent on a slow or busy page. It acts before the browser reaches the needed state. Replace timing guesses with a wait for a specific condition using Selenium’s waiting strategies.
Browser windows remain open after an error. Cleanup was skipped on an exceptional path. Put the automation in try/finally and call driver.quit() in the finally block.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Turn the script into repeatable tests

Most Selenium users automate tests for web applications, though Selenium can support other browser-automation tasks. Once a one-off script becomes a recurring check, organize the checks as tests and use a test runner such as pytest. Selenium’s organizing and executing Selenium code page includes a Python test example, but the page notes that this part of its documentation is incomplete, so use it as a starting point rather than an exhaustive guide.

Selenium IDE offers a record-and-playback path for people seeking less code; Selenium Grid is a route to scaling execution across machines or browsers. For a first local Python script, WebDriver is the direct route.

Use Selenium responsibly for scraping

Selenium can automate browser tasks on sites without a dedicated API, but automation is not permission to collect data. Check the target site’s terms and access rules: Selenium’s usage guidance warns that some sites prohibit scraping or block Selenium. Where a site provides an API for the task, evaluate that option and its terms before automating the browser.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Or skip the browser setup

If you only need a website screenshot or PDF rather than browser interaction, ScreenshotNeo can return one from a GET request. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in headers. Its MCP server gives AI agents screenshot, page-info, and PDF tools.

Install the Python client dependency with python -m pip install requests, then use this example (replace the target URL as needed; create an API key in your account):

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)

See the ScreenshotNeo API documentation for request details. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.

Frequently Asked Questions

Does Selenium work without a graphical desktop?

Whether a browser can run in a headless environment depends on the browser and runtime setup; consult the Selenium documentation for the browser-specific configuration you need.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can Selenium automate tasks other than tests?

Yes. Selenium supports browser automation beyond web-application testing, though site terms and access restrictions still apply.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.