Selenium Python Tutorial for Beginners: Setup and Your First Test
This selenium python tutorial takes you from an empty folder to a working, pytest-powered browser test. Install, locate elements, wait properly and avoid the mistakes that make beginner scripts flaky.
- Selenium 4 ships with Selenium Manager, so you no longer download ChromeDriver by hand.
- Install with
pip install selenium pytestinside a virtual environment. - Prefer explicit waits and stable locators over
time.sleep(). - Wrap the driver in a pytest fixture so every test gets a clean browser and always closes it.
You want to automate a browser with Python, but every guide seems to start with a different driver setup. This selenium python tutorial uses the current Selenium 4 workflow, where one pip command is enough to get going.
By the end you will have a small test suite that opens a real web form, fills it in, checks the result and runs from the command line. Every snippet was written against the official Selenium example page.
No automation background is needed. If Python itself is new to you, skim our Python tutorial for beginners first, then come back.
What you need before this Selenium Python tutorial
- Python 3.10 or newer. The latest Selenium release on PyPI (4.52.0 when I checked) lists Python 3.10 as the minimum.
- A browser such as Chrome, Firefox or Edge installed normally.
- A code editor and a terminal.
Selenium itself is a browser automation library. Python only sends commands; the browser does the real work. A small program called a driver sits between them. Since Selenium 4.6, Selenium Manager finds or downloads the right driver for you.
Setup in five minutes
Every selenium python tutorial starts here, so keep this part boring and repeatable.
Create a project folder and a virtual environment so the packages stay isolated. Our Python virtual environment tutorial explains each step in detail.
mkdir selenium-demo && cd selenium-demo
python -m venv .venv
# Windows: .venv\Scripts\activate macOS/Linux: source .venv/bin/activate
pip install selenium pytest
python -c "import selenium; print(selenium.__version__)"
If the last command prints a version number, the setup is done. There is no driver to download and no PATH to edit in a normal setup.
Your first script
Save this as first_test.py. It follows the pattern in the official Selenium getting started guide.
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
print(driver.title) # Web form
box = driver.find_element(By.NAME, "my-text")
button = driver.find_element(By.CSS_SELECTOR, "button")
box.send_keys("Selenium")
button.click()
message = driver.find_element(By.ID, "message")
print(message.text) # Received!
driver.quit()
Run it with python first_test.py. A browser window opens, the form is submitted and the script prints the page title and the confirmation text. Always end with driver.quit(), otherwise browser processes stay alive in the background.
Tip: Use webdriver.Firefox() or webdriver.Edge() to switch browsers. The rest of the script stays the same, which is the main reason teams choose Selenium.
Finding elements: locator strategies
Locators are the part of any selenium python tutorial that decides whether your tests survive next month’s redesign.
Every test depends on finding the right element. Selenium offers several strategies through the By class. Pick the most stable one you can.
| Strategy | Example | When to use it |
|---|---|---|
By.ID |
find_element(By.ID, "message") |
Best choice when the id is unique and stable |
By.NAME |
find_element(By.NAME, "my-text") |
Form fields |
By.CSS_SELECTOR |
find_element(By.CSS_SELECTOR, "form button") |
Flexible and fast; the everyday workhorse |
By.XPATH |
find_element(By.XPATH, "//button[text()='Submit']") |
Text matching or walking up to a parent |
By.LINK_TEXT |
find_element(By.LINK_TEXT, "Return to index") |
Links with fixed text |
Use find_elements (plural) to get a list. It returns an empty list when nothing matches, while find_element raises NoSuchElementException. Avoid long absolute XPaths like /html/body/div[2]/div[1]/button; they break whenever the layout changes.
Waiting correctly
Pages load in pieces. If your script clicks before a button exists, you get an exception, so beginners add time.sleep(5). That makes tests slow and still unreliable. Use an explicit wait instead:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, timeout=10)
message = wait.until(EC.visibility_of_element_located((By.ID, "message")))
assert message.text == "Received!"
The wait polls until the condition is true and returns as soon as it is, up to ten seconds. The official waits documentation also covers implicit and fluent waits, and we compare all three in Selenium WebDriver waits explained. Do not mix implicit and explicit waits in the same suite, because the timings can add up in confusing ways.
Turn the script into a pytest test
This is the step most selenium python tutorial articles skip, yet it is what separates a demo from a real suite.
A script that prints is not a test. A test asserts something and reports pass or fail. pytest gives you that, plus fixtures that handle the browser lifecycle. Create conftest.py:
import pytest
from selenium import webdriver
@pytest.fixture
def driver():
options = webdriver.ChromeOptions()
options.add_argument("--headless=new") # remove to watch the browser
d = webdriver.Chrome(options=options)
yield d
d.quit()
Now write test_form.py:
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://www.selenium.dev/selenium/web/web-form.html"
def test_page_title(driver):
driver.get(URL)
assert driver.title == "Web form"
def test_submit_form(driver):
driver.get(URL)
driver.find_element(By.NAME, "my-text").send_keys("Selenium")
driver.find_element(By.CSS_SELECTOR, "button").click()
msg = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.ID, "message")))
assert msg.text == "Received!"
pytest -v
The fixture starts a fresh browser for each test and always calls quit(), even when an assertion fails. That isolation is what keeps a growing suite stable.
Keep tests tidy with a page object
After this selenium python tutorial’s first tests pass, structure matters more than new features.
Once you have more than a few tests, move locators out of the test body. A page object is just a class that owns one page’s locators and actions.
class WebFormPage:
URL = "https://www.selenium.dev/selenium/web/web-form.html"
def __init__(self, driver):
self.driver = driver
def open(self):
self.driver.get(self.URL)
return self
def submit_text(self, text):
self.driver.find_element(By.NAME, "my-text").send_keys(text)
self.driver.find_element(By.CSS_SELECTOR, "button").click()
When the button changes, you fix one line instead of twenty tests. If you are still choosing a tool, see our list of the best test automation tools in 2026 and the Playwright vs Cypress comparison.
Common mistakes in a Selenium Python tutorial project
- Using sleep instead of waits. Replace every
time.sleep()with an explicit wait. - Forgetting to quit the driver. Use a fixture so cleanup is automatic.
- Copying browser-generated XPaths. They are brittle; write short CSS selectors.
- Testing against shared data. Create the data each test needs.
- Chasing old advice. Posts that pass a driver path to
webdriver.Chrome()or callfind_element_by_idtarget Selenium 3; the second form was removed in Selenium 4.
Final thoughts
A good selenium python tutorial project is small: one install command, one fixture, stable locators and explicit waits. Copy the files above, point them at your own app and add one test at a time. When the suite grows, add page objects and run it in CI.
Frequently asked questions
Is this selenium python tutorial suitable for beginners?
Yes. Python syntax is short, pip installs Selenium in one command and Selenium Manager handles the driver, so a first test takes minutes.
Do I still need to download ChromeDriver?
Normally no. Since Selenium 4.6 Selenium Manager locates or downloads a matching driver automatically.
Which Python version does Selenium need?
The current PyPI release lists Python 3.10 or newer. Check the project page for the exact requirement of the version you install.
Should I use pytest or unittest with Selenium?
Either works, but pytest fixtures make browser setup and cleanup shorter, and most teams prefer pytest.
Why does my Selenium test fail only sometimes?
Usually a timing problem. Replace sleeps with explicit waits and use stable locators instead of long XPaths.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.