Locators are html properties of a web element , which can be considered as an address of the element. An element will have various html properties. We can use Firebug extension or Chrome dev tools to identify different locators of an element.

Selenium Web Driver provides two different methods for identifying html elements .

  • FindElement  for WebDriver and WebElement Class. When locating element matching specified criteria, it looks through DOM( Document Object Model) for matching element and return the first matching element. If there are no matching element, it will throw NoSuchElementFoundException

  • FindElements for WebDriver and WebElement Class. When locating element matching specified criteria, it looks through DOM( Document Object Model) for matching element and return a list of all matching element. If there are no matching elements, then it will return an empty list .

Note: Both of them doesn’t support regular expression for finding element. Simple way to do that will be to get list of all elements and then iterate to find a matching regular expression

There are multiple criteria which we can use for looking for an element. FindElement and FindElements work exactly same way except for above difference. Different critieria are

  • driver.FindElement(By.Id())

  • driver.FindElement(By.Name())

  • driver.FindElement(By.ClassName())

  • driver.FindElement(By.TagName())

  • driver.FindElement(By.LinkText())

  • driver.FindElement(By.PartialLinkText())

  • driver.FindElement(By.CssSelector())

  • driver.FindElement(By.XPath())

Example:

1
2
3
4
5

WebElement _firstElement = driver.findElement(By.id("div1"));
WebElement _secondElementInsideFirstOne =_firstElement .findElement(By.linkText("username"));

IList<IWebElement> elements = driverOne.FindElements(By.ClassName(<span class="pl-s"><span class="pl-pds">“</span>green<span class="pl-pds">“</span></span>));

Using any attributes other than XPath and CssSelector are straight forward. More about using XPath and CssSelector in next blog.

Comments