Interacting with elements on a webpage helps us check if the site works as expected. It shows if buttons, links, and forms respond correctly.
0
0
Why element interaction drives test scenarios in Selenium Python
Introduction
When you want to test if clicking a button leads to the right page.
When filling out a form to see if the input is accepted and processed.
When checking if a dropdown menu shows the correct options.
When verifying that a link opens the correct website.
When testing if a checkbox can be selected and saved.
Syntax
Selenium Python
element = driver.find_element(By.ID, 'element_id') element.click() # To click on the element # Other interactions: element.send_keys('text') # To type text value = element.text # To get text from element
Use clear and stable locators like ID or name to find elements.
Common interactions include click, typing text, and reading text.
Examples
This clicks a button with the ID 'submit'.
Selenium Python
button = driver.find_element(By.ID, 'submit')
button.click()This types 'user123' into a text box named 'username'.
Selenium Python
input_box = driver.find_element(By.NAME, 'username') input_box.send_keys('user123')
This clicks a link with the visible text 'Home'.
Selenium Python
link = driver.find_element(By.LINK_TEXT, 'Home')
link.click()Sample Program
This test opens example.com, clicks the 'More information...' link, waits for the page to load, and checks if the new page has the expected text. It prints if the test passed or failed.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import time # Setup Chrome driver options options = Options() options.add_argument('--headless') # Run browser in background service = Service() driver = webdriver.Chrome(service=service, options=options) try: driver.get('https://example.com') # Find the More Information link and click it more_info_link = driver.find_element(By.LINK_TEXT, 'More information...') more_info_link.click() time.sleep(2) # Wait for page to load # Check if the new page contains expected text body_text = driver.find_element(By.TAG_NAME, 'body').text assert 'IANA-managed Reserved Domains' in body_text print('Test Passed: Link click navigated correctly.') except Exception as e: print(f'Test Failed: {e}') finally: driver.quit()
OutputSuccess
Important Notes
Always wait for the page or element to load before interacting to avoid errors.
Use meaningful locators to make tests reliable and easy to maintain.
Element interaction simulates real user actions, making tests realistic.
Summary
Element interaction is key to testing how users use a website.
Clicking, typing, and reading elements help verify functionality.
Good locators and waits make tests stable and trustworthy.