Selenium helps you control a web browser automatically. This lets you test websites like a real user would.
0
0
First Selenium script in Selenium Python
Introduction
You want to check if a website loads correctly.
You want to test if clicking a button works.
You want to fill a form and submit it automatically.
You want to check if a page shows the right text after an action.
Syntax
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By # Start browser driver = webdriver.Chrome() # Open a website driver.get('https://example.com') # Find an element element = driver.find_element(By.TAG_NAME, 'h1') # Check text assert element.text == 'Example Domain' # Close browser driver.quit()
Use webdriver.Chrome() to open Chrome browser.
Use By to find elements safely and clearly.
Examples
Open Firefox browser instead of Chrome.
Selenium Python
driver = webdriver.Firefox()
driver.get('https://example.com')Find a button by its unique ID.
Selenium Python
element = driver.find_element(By.ID, 'submit-button')Check if the page title contains 'Welcome'.
Selenium Python
assert 'Welcome' in driver.title
Sample Program
This script opens Chrome, goes to example.com, finds the main heading, checks its text, prints a success message, and closes the browser.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By # Open Chrome browser driver = webdriver.Chrome() # Go to example.com driver.get('https://example.com') # Find the main heading heading = driver.find_element(By.TAG_NAME, 'h1') # Check the heading text assert heading.text == 'Example Domain' print('Test passed: Heading text is correct.') # Close the browser driver.quit()
OutputSuccess
Important Notes
Make sure you have the correct browser driver installed (like chromedriver for Chrome).
Always close the browser with driver.quit() to free resources.
Use clear locators like By.ID or By.TAG_NAME for reliable tests.
Summary
Selenium scripts control browsers to test websites automatically.
Start with opening a browser, visiting a page, finding elements, checking text, and closing the browser.
Use assertions to confirm the website behaves as expected.