October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk8 min

How to Write Selenium Test Scripts

Write Selenium tests that navigate, locate, interact, wait for the right condition, assert the result, and always close the browser.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Selenium test script starts a browser, opens a page, finds elements, performs an action, checks the result, and closes the browser. The most reliable scripts use stable locators, wait for the exact condition they need, and make the expected result an assertion. Below is a complete Python example using Selenium’s sample form, followed by guidance on adapting it to your application and organizing it as a test.

What a Selenium test script does

Selenium WebDriver sends commands to a browser through a language-specific binding and a browser-specific driver. A small test follows a clear sequence: start a session, navigate, locate the relevant controls, interact, verify the outcome, and quit. The Selenium project describes WebDriver this way: “WebDriver drives a browser natively; learn more about it.” Selenium WebDriver overview.

The example below uses Python and the Selenium sample web form. It enters text, submits the form, waits for the response, asserts the result, and closes the browser even if an assertion fails.

Write a first test in Python

Install and prepare

Use a supported Python environment and install the Selenium binding:

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.
python -m pip install selenium

Make sure a compatible browser is available. Selenium Manager is included in the standard binding flow and generally handles browser-driver management without extra driver-management code in the test. Pinned browser versions, restricted environments, containers, and remote execution may need additional setup. See the Selenium getting-started guide for current setup details.

Runnable test script

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


driver = webdriver.Chrome()

try:
    driver.get("https://www.selenium.dev/selenium/web/web-form.html")

    wait = WebDriverWait(driver, 10)
    text_box = wait.until(
        EC.visibility_of_element_located((By.NAME, "my-text"))
    )
    text_box.send_keys("Selenium")

    submit = wait.until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "button"))
    )
    submit.click()

    confirmation = wait.until(
        EC.visibility_of_element_located((By.ID, "message"))
    )
    assert confirmation.text == "Received!", (
        f"Expected 'Received!', got {confirmation.text!r}"
    )
finally:
    driver.quit()

This follows the structure of Selenium’s “Write your first Selenium script” walkthrough. The assertion makes the script a test: it fails when the observed message does not match the expected message. The finally block ensures the browser session is closed on success or failure.

Run it and interpret the result

Save the code as test_form.py and run python test_form.py. A passing run ends without an exception. If the assertion fails, its message reports the text actually returned; a browser startup or element timeout points to a different setup or synchronization problem.

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.

Adapt the example to your application

  1. Choose a behavior to test. Write down the user action and the outcome that proves it worked, such as submitting valid details and seeing a confirmation.
  2. Open the application’s test environment. Replace the sample URL with the page under test. Keep test data isolated from production data.
  3. Locate the controls by stable attributes. Replace the sample name, CSS selector, and ID with locators that identify your form fields, buttons, and expected result.
  4. Wait for readiness. Wait for the element or state required by the next operation, especially on pages rendered or updated by JavaScript.
  5. Act and assert. Send input or click, then assert a user-visible outcome or other meaningful expected state.
  6. Always end the session. Keep cleanup in a finally block for a standalone script, or use your test framework’s teardown mechanism.

Choose locators that survive page changes

A locator identifies an element in the page DOM. Prefer a unique, predictable ID when the application provides one. A stable name or CSS selector can also be appropriate. Selectors tied to incidental nesting or broad tags can match the wrong element or break when the layout changes. The goal is a locator that clearly expresses which control the test intends to use.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Locator strategy When it fits What to check
ID A unique, stable ID exists for the control. Confirm it is unique and not generated differently on each page load.
Name A form control has a meaningful, stable name attribute. Check that the page does not contain multiple matching controls.
CSS selector A stable attribute or combination of attributes identifies the element. Avoid selectors that depend on fragile layout structure.
Class name A class reliably identifies the intended element. Classes may be shared across many elements or changed for styling.
Link text or partial link text The target is a link with stable, distinctive visible text. Text changes or duplicates can make the locator ambiguous.
Tag name The page has only one relevant element of that tag, or it is narrowed by another locator. Common tags such as button often match multiple elements.
XPath The relationship or attributes needed cannot be expressed simply with another strategy. Keep the expression readable and avoid coupling it to incidental DOM structure.

Selenium’s locator guide covers these strategies and their use in code: locating elements.

Wait for the condition the next step needs

A navigation reaching the browser’s configured document-ready state does not guarantee that a JavaScript-driven component has appeared or can be interacted with. In the example, the script waits for the text field to be visible and the submit button to be clickable; after the click, it waits for the confirmation. Match each wait to the next action or verification rather than guessing how many seconds the page needs.

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.

Explicit and implicit waits

An implicit wait applies globally to element lookups and defaults to zero. An explicit wait checks for a particular condition, such as visibility or clickability. Selenium warns that mixing implicit and explicit waits can produce unpredictable timeout behavior. Use condition-based explicit waits consistently for dynamic pages instead of relying on arbitrary fixed sleeps as the main synchronization strategy. Read the Selenium waits guide for the available conditions and details.

Turn a working script into a maintainable test

A one-off script proves that the browser flow can run. A test suite also needs repeatable setup, meaningful assertions, and cleanup. Selenium’s guide to organizing and executing tests explains using test frameworks and lifecycle setup and teardown.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Create the browser in test setup and close it in teardown, including when a test fails.
  • Give each test a clear expected result rather than only checking that an action did not raise an error.
  • Avoid sharing mutable browser state between unrelated tests; one test’s page or session changes can otherwise affect another.
  • Keep repeated actions and locators understandable so failures are easier to diagnose.

For a larger project, choose a test runner that fits the language and existing stack. Selenium bindings are available for multiple languages, and setup syntax depends on the selected binding. Choose by the language the team already maintains, required browser coverage, runner integration, and whether execution is local or remote. Selenium Grid is intended for running tests across multiple machines when distributed or parallel execution is needed; it is not necessary for a first local test. See the Grid documentation.

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
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failures and fixes

Symptom Likely cause What to do
Browser does not start or a driver error appears. The browser is unavailable, setup is restricted, or the environment uses pinned versions or remote execution. Confirm the browser is installed and review Selenium’s getting-started instructions for the environment. In managed environments, configure the driver or remote endpoint according to the project’s version and policy.
NoSuchElementException or an element lookup timeout. The locator does not match, the element has not appeared yet, or the page differs from the assumed state. Check the current DOM and locator, verify the page URL and state, and wait for the relevant condition before locating or using the element.
ElementNotInteractableException or click interception. The element is present but hidden, disabled, covered, or not yet ready to receive input. Wait for visibility or clickability as appropriate; check whether an overlay or application state blocks interaction.
Intermittent timeout on a JavaScript-heavy page. The test assumes page navigation means dynamic content is ready. Wait for a specific element or state change required by the next step, not a fixed delay alone.
Timeouts become difficult to predict. Implicit and explicit waits are mixed. Use one consistent synchronization approach; Selenium advises against mixing these wait types.
The test passes but does not prove the feature worked. The script performs actions without asserting an expected result. Add an assertion for the confirmation or state that demonstrates the requested behavior.
A browser remains open after a failed test. Cleanup runs only on the success path. Put quit() in a finally block or test-runner teardown.

Performance, reliability, and execution cost

Keep a test focused on one behavior and wait only for conditions it needs; long arbitrary sleeps slow the suite while still failing to guarantee readiness. Reusing clear locators and isolating state makes failures more interpretable. Parallel or remote execution can increase throughput for larger suites, but adds infrastructure and configuration, so introduce it when local execution no longer meets the project’s needs. Selenium’s Grid documentation describes the distributed option; the Selenium documentation cited here does not establish a universal execution-time or cost figure, which depends on browser, machine, application, and environment.

Or skip the browser setup

If the task is to capture a page image rather than exercise and assert an interactive browser flow, ScreenshotNeo is a screenshot API and MCP server for developers. It does not replace Selenium for functional browser tests. One GET request returns a PNG, JPEG, WebP, or PDF capture:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for parameters and response details. It accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents using Claude, Cursor, or another MCP client. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

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.

Sign up free for 1,000 screenshots a month with no card.

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.

Frequently Asked Questions

Which language should I use for Selenium tests?

Use the language already supported by your project and team; Selenium offers multiple language bindings, and no single binding is best for every stack.

Does Selenium require manually downloading a browser driver?

For a normal current binding setup, Selenium Manager handles standard browser and driver management. Restricted, pinned, containerized, or remote environments can require extra configuration.

Can Selenium Grid run tests in parallel?

Yes. Grid is Selenium’s option for running tests across multiple machines when distributed or parallel execution is needed.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.