Selenium 4 WebDriver commands operate inside a browser session: create it with browser options, navigate, locate and interact with elements, wait for the state your test needs, switch context for tabs or frames, capture evidence, and quit. The runnable examples below use the Python binding documented as Selenium 4.50.0; method names and feature availability differ across language bindings and releases.
Install Selenium and start a browser session
Install the Python package with python -m pip install selenium. This example uses Chrome and the Selenium 4 Python API. It does not assume a particular browser version or operating system; use a locally available compatible Chrome installation. Recent Selenium versions can use Selenium Manager to obtain a driver when one is not found locally, but setup behavior depends on the environment.
In Selenium 4, configure the browser through its Options class rather than reusing Selenium 3 Desired Capabilities examples. Creating the driver starts a WebDriver session, which is the context in which subsequent commands run.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
# Uncomment for headless operation:
# options.add_argument("--headless")
driver = webdriver.Chrome(options=options)
try:
driver.get("https://example.com")
print(driver.title)
finally:
driver.quit()
For a remote WebDriver session, provide an options instance that identifies the browser, along with the remote command endpoint appropriate to your infrastructure. See Selenium’s browser options documentation for supported configuration and page-load strategies.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitches#1 Best Overall
- 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.
Navigate and inspect the current page
Python’s get(url) opens a URL in the current tab and waits for the page load event under the configured page-load strategy. The other core navigation commands move through browser history or reload the current page:
driver.back()goes back.driver.forward()goes forward.driver.refresh()reloads the current page.
Use page properties to check what Selenium is addressing and to diagnose a failure:
driver.current_urlreturns the current URL.driver.titlereturns the document title.driver.page_sourcereturns a page-source snapshot.
Page source is useful for inspection, but it is not a replacement for locating and operating on live WebElements. A document reaching its readiness state does not guarantee that a single-page app has finished rendering the component a test needs.
Choose a page-load strategy deliberately
Selenium documents three page-load strategies. The default is normal; choosing a less blocking strategy can return control earlier, but leaves the test responsible for synchronizing with application state.
| Strategy | Readiness target | What the test still needs to handle |
|---|---|---|
normal |
Waits for document readiness state complete. |
JavaScript may still add or change page content after that state. |
eager |
Waits for interactive. |
Later loading and application updates may still be in progress. |
none |
Does not block on page readiness. | Explicit synchronization is essential before operations that depend on the page. |
For example, configure a strategy with options.page_load_strategy = "eager" before creating the driver. Confirm the available syntax for the selected binding and release in the options reference.
Rank #2
- 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 and perform interactions
Use find_element when one matching element is expected: if none is found, Selenium raises an exception. Use find_elements when zero or more matches are valid; it returns a list, which may be empty. Python locator strategies include ID, name, CSS selector, XPath, class name, tag name, and link text. Choose a stable locator tied to the page’s meaning and structure; no single strategy is universally best for every application.
from selenium.webdriver.common.by import By
search = driver.find_element(By.NAME, "q")
search.clear()
search.send_keys("Selenium WebDriver")
search.submit()
links = driver.find_elements(By.CSS_SELECTOR, "a")
print(f"Found {len(links)} links")
Common WebElement operations include:
element.click()to click.element.clear()andelement.send_keys("text")to edit text fields.element.textto read rendered text.element.get_attribute("href")to read an attribute.element.is_displayed()andelement.is_enabled()to check state.
For changing interfaces, check the state needed for the next action rather than assuming a located element is already ready. Selenium’s Web elements guide and browser interactions guide document the interaction model.
Wait for application state, not a guessed duration
Race conditions occur when a test issues a command before the page has reached the state the command requires. Selenium’s Waiting Strategies documentation calls this “one of the primary causes of flaky tests.” A navigation wait covers a document readiness target; it does not guarantee that a dynamic component has appeared or become usable.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Explicit wait: target a condition
An explicit wait polls for a specific condition and returns when it becomes true or raises a timeout error. This is generally the clearest choice for dynamic UI steps:
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
wait = WebDriverWait(driver, 10)
button = wait.until(
EC.element_to_be_clickable((By.ID, "continue"))
)
button.click()
The 10-second value is an example timeout, not a measured recommendation. Other useful conditions include presence or visibility of an element, and changes to a URL. Match the condition to what the next command needs.
Rank #3
- 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.
Implicit wait: session-wide lookup timeout
An implicit wait applies to element-location calls throughout the session. Its documented default is zero; configure it only when a session-wide lookup policy is intentional:
driver.implicitly_wait(5)
A failed lookup can then take up to the configured timeout to fail. Selenium warns that mixing implicit and explicit waits can produce unpredictable durations, so avoid combining them casually. The examples here use explicit waits and leave the implicit wait at its default.
Fixed sleep: elapsed-time delay
time.sleep(seconds) always consumes the chosen delay, even if the page becomes ready sooner, and can still be too short on a slow run. Use it when waiting for a fixed interval is itself part of the behavior under test, not as a general substitute for a condition.
Switch between tabs, windows, frames, and dialogs
Commands apply to the current browsing context. Before interacting with a new tab, iframe, or JavaScript dialog, switch to the relevant context.
Switch tabs or windows by handle
Track the handles before and after an action that opens a tab, then switch to the newly observed handle rather than assuming a fixed ordering:
Rank #4
- 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
before = set(driver.window_handles)
# Perform the action that opens a tab or window here.
wait.until(lambda d: len(set(d.window_handles) - before) == 1)
new_handle = (set(driver.window_handles) - before).pop()
driver.switch_to.window(new_handle)
print(driver.current_url)
# Return to the original window when needed:
driver.switch_to.window(driver.window_handles[0])
If the operation may open more than one window, identify the intended handle using the application’s expected state rather than selecting arbitrarily. See Working with windows and tabs.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Enter and leave an iframe
Switch into the frame before locating elements inside it. Switch back to the top-level document with default_content(), or to the containing frame with parent_frame().
frame = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "iframe.payment"))
)
driver.switch_to.frame(frame)
submit = wait.until(
EC.element_to_be_clickable((By.ID, "submit-payment"))
)
submit.click()
driver.switch_to.default_content()
The Python API also supports switching by frame name or index. Refer to Selenium’s frames guide for context-switching details.
Accept, dismiss, or read an alert
JavaScript alerts, prompts, and confirmations are browser dialogs. Switch to the alert and resolve it before continuing with page commands that depend on the dialog being closed:
alert = wait.until(EC.alert_is_present())
print(alert.text)
alert.accept() # Use alert.dismiss() to cancel instead.
For a prompt, enter text with alert.send_keys("value") before accepting. See JavaScript alerts, prompts and confirmations.
Best Value
- 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.
Capture evidence and end the session
A screenshot can preserve visual evidence at the point it is captured. Save it alongside a clear test name and failure details; a screenshot captured after the page has changed may not represent the state that caused the failure.
# Save a PNG screenshot to a file:
driver.save_screenshot("failure.png")
# Or obtain PNG bytes:
png_bytes = driver.get_screenshot_as_png()
To close only the current window, call driver.close(). To end the WebDriver session and close its associated windows, call driver.quit(). Put quit() in a finally block or your test framework's teardown hook so it also runs after an exception. The Selenium 4.50.0 Python WebDriver API documents these methods and screenshot formats.
Or skip the browser setup
If you need a website screenshot rather than interactive browser automation, ScreenshotNeo provides a screenshot API and MCP server. One GET request returns an image or PDF; see the ScreenshotNeo API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses include X-Page-Verdict and X-Billed headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots.
Free tools Windows power users keep installed
One-click scans. No signup required.
Sign up for ScreenshotNeo's free plan to try 1,000 screenshots a month without a card.
Use newer BiDi APIs with version care
The Selenium 4.50.0 Python API reference includes WebDriver BiDi-related modules for browsing contexts, input, browser, network, and script interfaces, including APIs to create, navigate, and close a tab. These are advanced, binding- and release-sensitive interfaces; check the documentation for the exact language binding and Selenium version you use rather than copying syntax across bindings.
Python WebDriver API reference, Selenium 4.50.0
Frequently Asked Questions
Why does `find_elements()` return an empty list instead of an error?
It is designed to return all matches and returns an empty list when none are present. Use `find_element()` when the test requires one match and should fail if it is absent.
Can I use these Python command examples unchanged in Java or JavaScript?
No. Selenium command names, imports, and feature availability vary by binding and release; consult the API documentation for the binding and version in your project.
Quick Recap
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.




