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
class LoginPage:
def __init__(self, driver):
self.driver = driver
self.email_input = (By.ID, 'email')
self.password_input = (By.ID, 'password')
self.login_button = (By.ID, 'login-btn')
def login(self, email, password):
WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.email_input)).send_keys(email)
self.driver.find_element(*self.password_input).send_keys(password)
self.driver.find_element(*self.login_button).click()
class DashboardPage:
def __init__(self, driver):
self.driver = driver
self.welcome_message = (By.ID, 'welcome-msg')
def is_welcome_message_displayed(self):
return WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.welcome_message)).is_displayed()
def test_login():
driver = webdriver.Chrome()
driver.get('https://example.com/login')
login_page = LoginPage(driver)
login_page.login('user@example.com', 'Password123!')
WebDriverWait(driver, 10).until(EC.url_to_be('https://example.com/dashboard'))
dashboard_page = DashboardPage(driver)
assert dashboard_page.is_welcome_message_displayed(), 'Welcome message should be visible'
driver.quit()
if __name__ == '__main__':
test_login()This script uses Selenium with Python to automate the login process.
We define Page Object Model classes for the login and dashboard pages. This keeps selectors and actions organized.
Selectors use By.ID which is reliable and less likely to break if the page layout changes.
We use explicit waits to wait for elements to be visible or for the URL to change. This avoids timing issues.
The test asserts that after login, the URL is correct and the welcome message is visible, confirming successful login.
This approach ensures the test is stable and easy to maintain, demonstrating why mastering selectors is key for reliability.