Selenium Locator Strategies

By class locator strategies :

By class provides several locator strategies to find elements on the web page. The findElement() and findElements() methods take a By object as parameter. We call them the By locators. E.g. :

public class LocatorStrategies{
   publi static void main(String[] arguments){
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.google.com");
      //By locators :
     // By searchBox = By.name("q"); 
        By searchBox = By.id("APjFqb");
   }
}

On a web page, we see different types of elements, textboxes, buttons, dropdowns, toggle buttons, radio buttons, plain texts, links, images etc. If we study the DOM, we can find the tags associated with these elements. Each element will have tag and some attributes(not necessary though).

  1. By.id(String id_value) : Id's of elements are unique on a webpage. So we use id of an element if it is available.

  2. By.name(String name_value)

    1. By. className(String className_value)

    2. By.xpath(String xpath_value) : Xpath is not an attribute.

    3. By.cssSelector(String cssSelector_value) : CssSelector is not an attribute.

    4. By.linkText(String linkText_value) : Only for links i.e. with <a> tags.

    5. By.partialLinkText(String partialLinkText_value) : Only for links i.e. with <a> tags. Can be used in case where link text is too long.

    6. By.tagName(String tagName_value) : Usage -- we want to list all images available on the web page, we can do it as below :

       List<WebElement> allImages = driver.fidElements(By.tagName("img"));