Software Testing · Selenium 4
Selenium Basics Explained for Complete Beginners
Quick summary — Selenium basics explained for complete beginners
Selenium basics for complete beginners come down to four skills: launching a browser with WebDriver, finding elements with locators, waiting properly, and asserting results. With Selenium 4 and Python you install one package, let Selenium Manager handle the driver, and write tests in pytest that click, type and check pages like a real user.
In this guide you will learn:
- What Selenium is — and how WebDriver controls a real browser.
- Your first script — install, launch Chrome and read a page title.
- Locators and waits — the two skills that make tests stable.
- pytest and Page Objects — how real test suites are organised.
- Interview questions — what QA interviewers ask about Selenium.
SECTION 01What Selenium is and your first script
Selenium is an open-source tool for automating web browsers. Its main part, Selenium WebDriver, lets code written in Python, Java, C#, JavaScript or Ruby control Chrome, Firefox, Edge or Safari. Testers use it to repeat checks such as 'can a user log in?' or 'does the form show an error for a wrong email?' on every new build, without doing it by hand each time. Selenium does not test mobile apps natively or desktop software; for those, other tools like Appium are used.
Since Selenium 4.6, a helper called Selenium Manager is built in. It finds or downloads the right browser driver automatically, so beginners no longer need to download chromedriver manually and set paths. You only need Python 3, a browser such as Chrome, and one command: pip install selenium. The script below opens a public practice form published by the Selenium project, prints its title and closes the browser.
| Part | What it is | Do I install it? | Beginner note |
|---|---|---|---|
| Selenium WebDriver | Library that sends commands to browsers | Yes, pip install selenium | The part you use daily |
| Selenium Manager | Finds or downloads browser drivers | No, bundled since 4.6 | Removes manual driver setup |
| Selenium IDE | Browser extension that records clicks | Optional | Good for exploring, weak for real suites |
| Selenium Grid | Runs tests on many machines and browsers | Later | Needed for parallel, cross-browser runs |
# 1. Check Python 3 is installed
python --version
# 2. Create and activate a virtual environment
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# 3. Install Selenium 4 and pytest
pip install selenium pytest
# 4. Confirm the version (should be 4.x)
python -c "import selenium; print(selenium.__version__)"
# first_test.py - open a page, read its title, close the browser
from selenium import webdriver
driver = webdriver.Chrome() # Selenium Manager sets up chromedriver
try:
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
print("Page title is:", driver.title) # Web form
assert driver.title == "Web form"
finally:
driver.quit() # always close the browser
# Run with: python first_test.py
SECTION 02Locators and waits: finding elements reliably
Every Selenium action starts by finding an element. In Selenium 4 you use driver.find_element(By.X, "value"), where By can be ID, NAME, CSS_SELECTOR, XPATH, CLASS_NAME, TAG_NAME, LINK_TEXT or PARTIAL_LINK_TEXT. The older helpers such as find_element_by_id were removed in Selenium 4, so old tutorials that use them will fail. Prefer stable locators: an ID or a dedicated test attribute is best, a short CSS selector is next, and long absolute XPaths copied from browser tools are fragile.
The second skill is waiting. Modern pages load content with JavaScript, so an element may not exist the instant the page opens. Beginners often add time.sleep(5), which makes tests slow and still flaky. The right tool is an explicit wait: WebDriverWait with expected_conditions keeps checking until a condition is true or a timeout passes. Avoid mixing implicit and explicit waits in the same suite, because the combined timeouts behave unpredictably.
| Locator | Example | Strength | Watch out for |
|---|---|---|---|
| By.ID | By.ID, "login-btn" | Fast and usually unique | Auto-generated IDs that change |
| By.NAME | By.NAME, "my-text" | Common on form fields | Repeated names in big forms |
| By.CSS_SELECTOR | By.CSS_SELECTOR, "button[type='submit']" | Flexible and readable | Over-long nested selectors |
| By.XPATH | By.XPATH, "//button[text()='Submit']" | Can match by visible text | Absolute paths like /html/body/div[3] |
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")
text_box = driver.find_element(By.NAME, "my-text")
password = driver.find_element(By.NAME, "my-password")
textarea = driver.find_element(By.NAME, "my-textarea")
submit = driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
text_box.send_keys("Selenium")
password.send_keys("secret123")
textarea.send_keys("Learning locators")
submit.click()
message = driver.find_element(By.ID, "message")
print(message.text) # Received!
driver.quit()
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
driver = webdriver.Chrome()
try:
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
driver.find_element(By.NAME, "my-text").send_keys("Selenium")
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
# Wait up to 10 seconds for the confirmation text
wait = WebDriverWait(driver, 10)
message = wait.until(
EC.visibility_of_element_located((By.ID, "message"))
)
assert message.text == "Received!"
finally:
driver.quit()
SECTION 03From scripts to real tests: pytest and Page Objects
A script that prints things is a start, but real automation needs tests that pass or fail clearly. pytest is the most popular Python test runner: any function whose name starts with test_ becomes a test, plain assert statements check results, and fixtures handle setup and teardown such as opening and closing the browser. Tests should be independent, so each one gets a fresh browser and can run in any order.
As the suite grows, copying locators into every test becomes a maintenance problem. The Page Object Model solves this by putting each page's locators and actions in one class. Tests then read like plain steps — open the form, fill the name, submit, check the message — and when the page changes you update one file. Headless mode, using the --headless=new Chrome argument, lets the same tests run without a visible window on CI servers.
| Concept | What it does | Example | Why beginners need it |
|---|---|---|---|
| pytest test | Function that passes or fails | def test_submit_form(driver): | Clear results, easy reports |
| Fixture | Shared setup and teardown | @pytest.fixture driver | Browser always closes |
| Page Object | Class holding a page's locators and actions | WebFormPage.submit() | One place to fix changes |
| Headless run | Browser without visible window | --headless=new | Runs on CI servers |
# conftest.py - shared browser fixture
import pytest
from selenium import webdriver
@pytest.fixture
def driver():
options = webdriver.ChromeOptions()
options.add_argument("--headless=new") # remove to watch the browser
drv = webdriver.Chrome(options=options)
yield drv
drv.quit()
# pages/web_form.py - Page Object (add an empty pages/__init__.py)
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class WebFormPage:
URL = "https://www.selenium.dev/selenium/web/web-form.html"
TEXT = (By.NAME, "my-text")
SUBMIT = (By.CSS_SELECTOR, "button[type='submit']")
MESSAGE = (By.ID, "message")
def __init__(self, driver):
self.driver = driver
def open(self):
self.driver.get(self.URL)
return self
def submit_text(self, value):
self.driver.find_element(*self.TEXT).send_keys(value)
self.driver.find_element(*self.SUBMIT).click()
def message(self):
wait = WebDriverWait(self.driver, 10)
return wait.until(EC.visibility_of_element_located(self.MESSAGE)).text
# test_web_form.py - run with: python -m pytest -v
from pages.web_form import WebFormPage
def test_page_title(driver):
WebFormPage(driver).open()
assert driver.title == "Web form"
def test_submit_shows_confirmation(driver):
page = WebFormPage(driver).open()
page.submit_text("Hello Selenium")
assert page.message() == "Received!"
SECTION 04Selenium beginner templates and checklists
Use these to set up a clean project, write test cases before code and debug failures methodically.
SELENIUM + PYTEST PROJECT LAYOUT
selenium-basics/
.venv/ (not committed)
pages/
__init__.py
web_form.py Page Objects
tests/
test_web_form.py
conftest.py browser fixture
requirements.txt selenium, pytest
pytest.ini [pytest] testpaths = tests
README.md how to install and run
.gitignore .venv/ __pycache__/ .pytest_cache/
MANUAL TEST CASE -> AUTOMATION
ID : TC_FORM_01
Title : Submitting the web form shows confirmation
Pre-condition : Browser open, form page loaded
Steps :
1. Enter text in 'Text input'
2. Click Submit
Expected : Message 'Received!' is visible
Locators : NAME=my-text, CSS=button[type='submit'], ID=message
Wait needed? : Yes - visibility of #message
Automated in : tests/test_web_form.py::test_submit_shows_confirmation
WHEN A SELENIUM TEST FAILS
[ ] Read the exception type
NoSuchElementException -> locator wrong or page not ready
TimeoutException -> condition never became true
ElementClickIntercepted -> something covers the element
StaleElementReference -> page re-rendered; find it again
[ ] Run without --headless and watch
[ ] Save a screenshot: driver.save_screenshot("fail.png")
[ ] Check the locator in browser DevTools (Ctrl+F in Elements)
[ ] Replace any time.sleep with an explicit wait
[ ] Confirm the element is not inside an iframe
SECTION 05Tips for Selenium beginners
These habits save hours of frustration in your first weeks with Selenium:
- Learn basic HTML and CSS selectors first — you cannot locate elements well if you cannot read the page structure.
- Ignore tutorials using find_element_by_* — that syntax was removed in Selenium 4; use find_element(By..., ...).
- Never rely on time.sleep — use WebDriverWait with a specific expected condition.
- Keep tests independent — each test should set up its own data and not depend on another test running first.
- Automate stable, repeated checks — login, search and checkout flows give more value than one-off visual checks.
SECTION 06Interview Q&A — Selenium basics
Q1What is Selenium WebDriver?
Selenium WebDriver is a library and protocol for controlling real browsers from code. Your test sends commands such as open a URL, find an element or click, a browser driver translates them, and the browser executes them. In Selenium 4 it follows the W3C WebDriver standard.
Q2What is the difference between implicit and explicit waits?
An implicit wait sets a global time Selenium keeps trying to find any element. An explicit wait, using WebDriverWait and expected conditions, waits for one specific condition, such as visibility or clickability. Explicit waits are more precise, and mixing both types is discouraged.
Q3What is the difference between find_element and find_elements?
find_element returns the first matching element and raises NoSuchElementException if none exist. find_elements returns a list of all matches, which is empty if nothing matches. find_elements is useful for counting items or checking that something is absent.
Q4What is the Page Object Model?
It is a design pattern where each web page is represented by a class holding its locators and actions. Tests call these methods instead of using locators directly, which reduces duplication and means a UI change usually needs an update in one place only.
Q5What is a StaleElementReferenceException?
It happens when you hold a reference to an element that has since been removed or re-rendered in the page, for example after a refresh or JavaScript update. The fix is to locate the element again, often inside an explicit wait, after the page changes.
SECTION 07Test yourself — Selenium basics
Five questions. No sign-up.
0 / 5Pick an answer to see why it is right or wrong.
SECTION 08Frequently asked questions
Is Selenium easy to learn for complete beginners?
Selenium is approachable if you first learn basic programming in one language, such as Python, plus simple HTML and CSS selectors. The commands themselves are few. Most beginner struggles come from weak locators and missing waits, which improve quickly with guided practice on real pages.
Which language is best for learning Selenium?
Java and Python are both widely used with Selenium. Python is often easier for beginners because of its short, readable syntax and pytest. Many company frameworks use Java with TestNG or JUnit, so check local job posts and learn the language they mention most.
Do I need to download chromedriver for Selenium 4?
Usually not. Since Selenium 4.6, Selenium Manager automatically finds or downloads a matching driver when you create webdriver.Chrome(). You may still configure drivers manually in restricted corporate networks or when you need a specific version for a test environment.
Can Selenium test mobile apps and desktop applications?
Selenium WebDriver automates web browsers only. For native mobile apps, teams commonly use Appium, which follows a similar WebDriver approach. Desktop applications need other tools. Selenium can still test mobile web pages by running browsers in mobile emulation or on real devices through a grid.
Is Selenium still worth learning with newer tools like Playwright?
Yes. Selenium remains widely used in existing automation suites, supports many languages and browsers, and teaches core concepts that transfer to Playwright and Cypress. Learning Selenium well, along with good test design, makes picking up newer tools much easier later.
SECTION 09Related reads
Classroom & online · Noida
Learn Selenium automation hands-on
Our Automation Testing Training Course covers Selenium WebDriver, locators, waits, test frameworks and Page Object design through practical projects — in Noida, Delhi and live online.
Talk to a counsellor for current fees- Hands-on Selenium projects
- Framework & Page Object design
- 1:1 mock interviews
- Weekday & weekend batches