Action methods help you perform tasks on a web page like clicking buttons or typing text. They keep your test code clean and easy to understand.
0
0
Action methods in page class in Selenium Python
Introduction
When you want to click a button on a web page during a test.
When you need to enter text into a form field automatically.
When you want to select an option from a dropdown menu.
When you want to check if a page element is visible before interacting.
When you want to reuse common page actions in multiple tests.
Syntax
Selenium Python
from selenium.webdriver.common.by import By class PageClass: def __init__(self, driver): self.driver = driver def action_method(self): element = self.driver.find_element(By.ID, 'element_id') element.click()
Action methods are inside a page class that represents a web page.
They use locators to find elements and perform actions like click or send keys.
Examples
This method clicks the login button on the page.
Selenium Python
def click_login_button(self): login_button = self.driver.find_element(By.ID, 'loginBtn') login_button.click()
This method types the given username into the username field.
Selenium Python
def enter_username(self, username): username_field = self.driver.find_element(By.NAME, 'username') username_field.clear() username_field.send_keys(username)
This method checks if an error message is visible on the page.
Selenium Python
def is_error_displayed(self): error = self.driver.find_element(By.CLASS_NAME, 'error') return error.is_displayed()
Sample Program
This test script opens a login page, enters username and password using action methods, clicks login, and prints a confirmation message.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By class LoginPage: def __init__(self, driver): self.driver = driver def enter_username(self, username): user_field = self.driver.find_element(By.ID, 'username') user_field.clear() user_field.send_keys(username) def enter_password(self, password): pass_field = self.driver.find_element(By.ID, 'password') pass_field.clear() pass_field.send_keys(password) def click_login(self): login_btn = self.driver.find_element(By.ID, 'loginBtn') login_btn.click() # Test script driver = webdriver.Chrome() driver.get('https://example.com/login') login_page = LoginPage(driver) login_page.enter_username('testuser') login_page.enter_password('mypassword') login_page.click_login() print('Login action performed') driver.quit()
OutputSuccess
Important Notes
Use clear() before send_keys() to avoid leftover text.
Keep locators private inside the page class for easy updates.
Action methods should do one clear task for easy reuse.
Summary
Action methods perform tasks on web page elements inside a page class.
They help keep test code clean and reusable.
Use them to click, type, or check elements during tests.