XPath with attributes helps you find specific elements on a web page by looking at their properties. This makes your tests more accurate and reliable.
0
0
XPath with attributes in Selenium Python
Introduction
When you want to click a button with a unique id or class.
When you need to check if a specific input field is present by its name attribute.
When you want to verify a link with a certain href value.
When multiple elements have the same tag but different attributes.
When you want to select elements based on custom data attributes.
Syntax
Selenium Python
//tagname[@attribute='value']Use double slashes // to search anywhere in the page.
Attributes are inside square brackets with @ before the attribute name.
Examples
Selects an input element with id 'username'.
Selenium Python
//input[@id='username']
Selects a button element with class 'submit-btn'.
Selenium Python
//button[@class='submit-btn']Selects a link with the exact href 'https://example.com'.
Selenium Python
//a[@href='https://example.com']Selects a div with a custom attribute 'data-test' equal to 'login-form'.
Selenium Python
//div[@data-test='login-form']Sample Program
This script opens a browser, goes to a login page, finds the username input using XPath with an id attribute, checks if it is visible, prints a success message, and closes the browser.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By # Start the browser browser = webdriver.Chrome() # Open a simple test page browser.get('https://example.com/login') # Find the username input by its id attribute username_input = browser.find_element(By.XPATH, "//input[@id='username']") # Check if the input is displayed assert username_input.is_displayed(), 'Username input should be visible' print('Test passed: Username input found and visible') # Close the browser browser.quit()
OutputSuccess
Important Notes
Always use unique attributes to avoid selecting the wrong element.
Use browser developer tools to inspect elements and find their attributes.
XPath is case-sensitive for tag names and attribute values.
Summary
XPath with attributes helps find elements by their properties.
Use //tagname[@attribute='value'] format.
It makes tests more precise and reliable.