课程: Test Automation with Selenium WebDriver for Java
Locator strategies
- [Instructor] WebDriver interacts with web elements via the Document Object Model, also known as the DOM. The DOM represents the structure of a webpage, allowing WebDriver to access and manipulate elements within it. Fortunately, WebDriver provides several strategies to locate elements within the DOM. Here are the most commonly used locators. Let's look at each one. Web elements can have an id attribute, which should be unique within the page. Locating an element by its id is usually the fastest and most reliable method, and should be your first choice when available. Elements can also have a name attribute, which is not required to be unique. The class attribute can be used to find elements, but be careful because classes are often added for styling with CSS, and therefore could change more frequently than other locators. The tag name strategy locates elements by their HTML tag. It's useful for finding elements that do not have other attributes. However, there could be lots of elements with a given tag within the DOM, so you need to narrow down specifically which element you want to interact with. You can use the exact text of anchor tags to locate them. Use this strategy with caution as the text of a link can change more frequently than other locators. CSS selectors are very powerful and can locate elements based on their CSS properties. This method is quite flexible and can target complex element structures. When there's no id available, CSS selectors are commonly used with WebDriver because they allow you to aggregate multiple locators to narrow down the exact one you're targeting. With WebDriver, XPath has the same purposes as CSS selectors, which is to form more complex locator queries. Its syntax just differs. Because you're automating actions, it's extremely important to choose your element locator strategy wisely. You want to choose the most reliable, change-resistant locator possible. ids should be used whenever possible for its speed, uniqueness, and reliability. Names are your best option when ids are not available. Class names should only be used when the element is not contained in the id or name attribute. CSS selectors and XPath are powerful and flexible strategies that should be used for complex queries that include more than one locator. Tag names are handy for locating multiple elements of the same type or when no unique identifiers are available. And link text is best for anchor elements that do not contain any other attributes. By selecting the right locator strategy, you can minimize the risk of automation failures due to changes in the webpage's structure.