Tuesday, 5 August 2014

Locators In Selenium

Locators
Selenium uses what is called locators to find and match the elements of your page that it needs to interact with. There are 8 locators strategies included in Selenium:
  • Identifier
  • Id
  • Name
  • Link
  • DOM
  • XPath
  • CSS
  • UI-element
 Identifier
Works with the ID and name attributes of your html tags. Let’s consider the following example:
<html>
<body>
<form id=”login”>
<input name=”username” type=”text”/>
<input name=”password” type=”password”/>
<input name=”submit” type=”submit” value=”Continue!”/>
</form>
</body>
</html>
Valid locators for this snippet are :
  • identifier=login
  • identifier=username
  • submit
Id
The Id strategy looks for an element in the page having an id attribute corresponding to the specified pattern. <label id=”my_id” /> will be matched by a locator like id=my_id or just my_id
 Name
Like the Id strategy, but on the name attribute. You can also specify a filter to refine your locator. Currently, there are two filter types :
  • Value : matches elements with a name attribute and where the value follows a pattern. The following example illustrates the interest of filters :
  • <html>
  •  <body>
  •    <div id=”pancakes”>
  •      <button type=”button” name=”pancake” value=”Blueberry”>Blueberry</button>
  •      <button type=”button” name=”pancake” value=”Banana”>Banana</button>
  •      <button type=”button” name=”pancake” value=”Strawberry”>Strawberry</button>
  •    </div>
  •  </body>
</html>
Link
This strategy is intended to select links only and selects the anchor element containing the specified text: link=The text of the link
DOM
The DOM strategy works by locating elements that matches the javascript expression refering to an element in the DOM of the page.
  • dom=document.div['pancakes'].button[0]
  • document.div[0].button[2]
  • dom=function foo() { return document.getElementById(“pancakes”); }; foo();
XPath
While DOM is the recognized standard for navigation through an HTML element tree, XPath is the standard navigation tool for XML; and an HTML document is also an XML document (xHTML). XPath is used everywhere where there is XML. Valid XPath locators can be:
  • xpath=//button[@value="Blueberry"]: matches the Blueberry button
  • //div[@id="pancakes"]/button[0]: same thing
CSS
The CSS locator strategy uses CSS selectors to find the elements in the page. Selenium supports CSS 1 through 3 selectors syntax excepted CSS3 namespaces

No comments:

Post a Comment