Selenium and Java

Sunday, 22 March 2015

Selenium - Different types of Web element locator in Selenium WebDriver


Locating elements in WebDriver can be done on the WebDriver instance itself or on a WebElement.we have to use finelement method. it returns WebElement object if element found else returns nosuchelementfound exception.
Different types of locator as below.

1.  By.ID: 

Locating web element by ID is simplest and easy way. Use this when we know id attribute of an element

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.ID("txtboxid"));

If web element ID not defined by UI developer or element ID is not unique or its generated at run time then we can not use By.ID locator.

2. By.Name : 

Like ID we can also use Name attribute of web element to locate the same.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.Name("txtboxname"));

3. By.className:

We can also class attribute to locate web element . In case of multiple element with same class name than it returns first element with classname.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.className("txtclassname"));

4. By.linkText

 We can use link text to locate a link element.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.linkText("txtlink"));

5. By.partialLinkText

Like linkText we can also locate link element by partial link text.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.partialLinkText("txtlinktext"));

6.  By.Xpath:

Web element can be located using xpath. At a high level, WebDriver uses a browser’s native XPath capabilities wherever possible.  Xpath is useful when we don't know ID or Name attribute.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.Xpath("//html/body/form[1]"));

7. By.CSS Selector:

Like Xpath we can also use CSS selector. CSS is cascade style sheet.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.cssSelector("//html/body/form[1]"));

No comments:

Post a Comment