How selenium identifies elements on browser – Selenium locators
Selenium provides different type of locators to uniquely identify web elements on the browser (HTML content)To view the HTML content and spy on an webelement:
see below screenshot for the steps to get the id of a webelement, in this case we want to get the id of email field on facebook.com
<span style="color: #000000;">WebElement txt_uname = driver.findelement(By.id("email"));
By locator = By.id("email");
WebElement txt_uname = driver.findelement(locator);</span>
Look for the html content with keyword -> name = <‘somevalue’> as shown below
Special case for by name: If multiple elements have the same value for a name attribute,
in the below screenshot, 2 radiobuttons have same name as tripType (Mercury tours application, flight finder page, comes after login)
Then use filters to further refine location strategy. The default
filter type is value (matching the value attribute),
so in our case:
name = tripType value = oneway
name = tripType value = twoway
in this way, we distinguish both the radiobuttons
NOTE: Above mentioned locators allow Selenium to test a UI element independent of its location on the page. So if the page structure and organization is altered, we still can identify the object.
This is a simple method of locating a hyperlink in your web page by using the
text of the link (i.e the name given to the ‘a’ tag in the html content).
If two links with the same text are present, then the first
match will be used.
by CSS Selector:
CSS (Cascading Style Sheets) is a language for describing the rendering of HTML
and XML documents. CSS uses Selectors for binding style properties to elements
in the document.
let’s see how we can derive the css selectors from the html content:
Note: inner text is the exact word that is displayed on browser for that element.
XPath is the language used for locating nodes in an XML document and HTML can
be an implementation of XML (XHTML).
Selenium opens up all sorts of new possibilities such as locating the
third checkbox on the page.
XPath locators can also be
used to specify elements via attributes other than id and name.
For more detailed description, please refer here.
Note: ID identifies faster than other locators, but some times we will not have ID value unique(changes time to time) or no ID for an element, so as of me flexible way is to use XPATH / CSS Selector.
Content posted is based on learning or working experience,
Share the post with others if find useful,
Any queries?, leave comments or discuss on our facebook:qavalidation.com, Thanks!