In this article, you’ll learn how to interact with form elements on a web page using XPath locators in Selenium WebDriver. By locating elements like input fields and buttons with XPath, you’ll automate actions such as typing text and clicking buttons. This is a fundamental skill in web automation and testing.
Below you can find the snippet of the HTML code used.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Form</title>
</head>
<body>
<form id="loginForm">
<input id="username" class="input-field" type="text" placeholder="Username">
<input id="password" class="input-field" type="password" placeholder="Password">
<button class="btn primary" type="submit">Login</button>
</form>
</body>
</html>
Step 1: Setup and Open the Web Page
Start by importing necessary modules and initializing the WebDriver. Open the target HTML form using its URL.
Step 2: Locate and Interact with the Username Input Field
This XPath //input[@id='username']
targets an <input>
element with the specific attribute id="username"
and used the send_keys()
method to enter text into the input field.
Step 3: Locate and Interact with the Password Input Field
This XPath //input[@id=’password’] selects the <input>
element with the id="password"
and used the send_keys()
method to type in the password.
Step 4: Locate and Click the Login Button
This XPath //button[text()='Login']
targets a <button>
element whose text content is exactly “Login” and uses the click()
action method to simulate a click on the button.
Step 5: Handle Exceptions and Wait Before Closing
Use a try-except
block to catch any errors during element interaction. Print a success or error message accordingly. Add a delay before closing the browser to observe the actions performed.
Final Code
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open the form page (localhost example)
url = "http://127.0.0.1:5500/css-selector-form.html"
driver.get(url)
try:
# Locate username input field using XPath
username_field = driver.find_element(By.XPATH, "//input[@id='username']")
username_field.send_keys("testuser")
# Locate password input field using XPath
password_field = driver.find_element(By.XPATH, "//input[@id='password']")
password_field.send_keys("password123")
# Locate login button using XPath and click it
login_button = driver.find_element(By.XPATH, "//button[text()='Login']")
login_button.click()
print("Form filled and login button clicked successfully!")
except Exception as e:
print("Error:", e)
# Wait before closing the browser
time.sleep(5)
driver.quit()
Let’s see the code in action.
with this you have learned how to locate elements using XPath.
Similar Posts
How to handles Drop down in selenium
How to Handle Alerts and Popups in Selenium
Locating Strategies in Selenium : Locating by Id
Installing Selenium and Configuring Web Driver
Selenium Python Example: How to run your first Test?