LOCATORS IN SELENIUM

 

Selenium  locators  are  used  to  uniquely  identify  the  HTML  elements  and  interact  with  these  HTML  elements such as  button,text  boxes , links  etc. in  the  Document  Object  Model (DOM)  during  automation.

 

 

 

 

 

Selenium  WebDriver  supports  8  primary  locator  types  through  the  By  class.

 

  • ID:  This  locator  locates  the  elements  using  the  id  attribute . This  is  the  fastest  and  most  reliable  methods  because  IDs  should  be  unique  on  a  page.

             Example:

             driver.findElement(By.id(“signin-button”));

 

  • Name : This  locator  locates  the  target  elements  using  the  name  attribute , commonly   used  for   form  controls  like  input   fields .

 

           Example :

              driver.findElement(By.name(“gift”));

 

  •     Tag Name :  This  locator   locates  the  elements   based  on  their  HTML  tag (e.g. <a> , <div> , <button>, <input> ) , which  is  useful  for  finding  groups  of  similar  elements .

             Example :

             driver.findElement(By.tagName(“input”));

 

  •   Link  Text :  This  locator  is  used   specifically  for  anchor  tags (<a> ) , it  matches  the  exact  visible  text  of  a  hyperlink.

            Example :

             driver.findElement(By.linkText(“Submit now ” ) );

 

  •   Partial Link  Text : This  locator  is  similar  to  Link  Text  but  allows  matching  a  substring  of  the  hyperlink’s  text .

           Example :

           driver.findElement(By.partialLinkText(“Submit”));

 

  • CSS  Selector : This  locator  uses  CSS  syntax  to  find  elements.  It is  more  flexible  than  ID  or   Nmae  and  faster  than  Xpath.

             

             Example :

             WebElement signinButton=driver.findElement(By.cssSelector(“#signinBtn”));

              signinButton.click();

 

  • Xpath :  This  locator  is  very  useful  for  navigating  the  XML/HTML  structures . It  can  locate  elements  relative  to  others  and  find  them  based  on  complex  attributes . 

            Example : 

           driver.findElement(By.xpath(“//input[@type=’text’]”));

 

 

 

 

 

 

 

Advanced  Locator  Concepts :

 

  • Relative  Locators (Selenium 4+ ) :  Relative Locators  allow  to  find  elements  based  on  their  position  relative  to  other  elements  using  terms   like  above , below , toRightOf , toLeftOf  and  near.
  • Chaining  and  Multiple  Matches :   Use   findElements()  method  to  return  the  list  of  all   matching  elements  instead  of  just  the  first  one .

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *