These are the Locator Types for Web Objects:
-
ID: This should be your first choice, if available because they are unique within a page. For example, you are testing a login form that has input fields for username and password, each with unique IDs. The HTML might look something like this
<input id="username">and<input id="password">. In this case, you can use the ID locator to identify these fields in your test. -
Name: A reliable choice, especially for form elements. However, names are not always unique within a page. So, exercise caution when using this locator. Consider a scenario where you're testing a registration form with multiple fields like first name, last name, email, etc. The HTML for the first name field might look like this
<input name="firstName">. Here, you can use the Name locator to identify the first name field. -
Link: The best choice for links, provided the link text is unique on the page. If you are testing a navigation menu with links to different sections of the website, each link might be represented in HTML like this
<a href="/contact">Contact Us</a>. In this case, you can use the Link locator with "Contact Us" to identify the contact link. -
CSS: An excellent choice when you need more flexibility than what ID or Name can provide. They are also typically easier to understand than XPath, especially for complex selections. Suppose you are testing a webpage that has multiple elements with the same CSS class. For example, there might be several buttons with the class "cta-button". The HTML for one button might look like this
<button class="cta-button">Sign Up</button>. Here, you can use the CSS locator with.cta-buttonto identify all the call-to-action buttons. -
XPath: The most flexibility to select elements in ways that other locators cannot. However, XPath expressions can become complex and difficult to read. Consider a scenario where you are testing a blog page that has multiple posts, and you want to select the title of the third post. The HTML might not provide unique IDs or names, but you could use XPath to navigate the structure of the page. An XPath like
//div[@class='post']/h2[3]could be used to select the third post title.