In Selenium testing, choosing the right selector is important for test reliability. Which reason best explains why CSS selectors are often preferred over XPath?
Think about speed and simplicity when tests run in browsers.
CSS selectors are faster and easier to read and maintain than XPath in most browsers, which helps tests run reliably and quickly.
You want to locate a login button that has the HTML: <button id='loginBtn' class='btn primary'>Login</button>. Which locator is the most reliable?
IDs are unique and stable if available.
Using the ID locator is most reliable because IDs are unique on the page and less likely to change than classes or text.
Given a checkbox element located as checkbox = driver.find_element(By.ID, 'agree'), which assertion correctly checks if it is selected?
Check the Selenium method that returns selection state.
The is_selected() method returns True if the checkbox is checked. Checking the 'checked' attribute may not always be reliable.
Consider this Selenium code snippet:
element = driver.find_element(By.CSS_SELECTOR, 'div.content > span.title')
The element is not found, but the HTML is:
<div class='content'><h1 class='title'>Welcome</h1></div>
Why does the locator fail?
Compare the tag names in the selector and HTML.
The selector looks for a inside with class 'title', so the locator does not match.
In a large Selenium test framework, why does mastering selectors contribute most to test stability?
Think about how selectors affect test failures due to page changes.
Precise and robust selectors help tests find elements reliably even if the page structure changes slightly, reducing flaky failures and improving overall stability.