Locating WebElements

Element-locating functions are the building blocks of Selenium tests. These methods handle Ajax calls using timeouts and wait conditions to search and locate elements within a web page. There is no fixed strategy that you can follow to locate an element; it depends on the user ideology and their comfort level in locating the web elements.

An element can be located using any kind of locator type. Selenium WebDriver uses locators to interact with elements present in a web page. The following is the list of locator types used in Selenium WebDriver to locate web elements:

  • By.id
  • By.name
  • By.xpath
  • By.cssSelector
  • By.className
  • By.linkText
  • By.tagName
  • By.partialLinkText

The following is the syntax to use locatorType:

driver.findElement(By.locatorType("path"))

The following is an example for locatorType:

driver.findElement(By.id("sblsbb")).click();

Prioritize the locator type in this order: id > name > css > xpath. The cssSelector locator type is a good pick to work with Ajax calls. Always try to avoid locating elements using XPath locators. Remember that Internet Explorer tests often fail to respond to XPath locators. The XPath locator type is of two categories, namely, absolute XPath / and relative XPath //. Consider an element on the Google search page:

Absolute XPath

Relative XPath

//html/body/div[1]/div[3]/form/div[2]/div[2]/div[1]/div[1]/div[3]/div[1]/div[3]/div[1]/input[1]

//input[@id='lst-ib']

Here, both the absolute and relative XPath point to the same element.

Note

To know more on XPath functions and axes, please refer to the following links:

Let's take a look at Selenium WebDriver's element-locating functions, which are as follows:

  • findElement(): This element locates the first element within the current page. The following is the syntax for this function:
    driver.findElement(By.locatorType("path"));

    The following is an example where Selenium WebDriver locates the Google search text field using the findElement() method:

    driver.get("https://www.google.com");
    WebElement element = driver.findElement(By.id("lst-ib"));
  • findElements(): This element locates all the elements within the current page. The following is the syntax for this function:
    List<WebElement> elements = driver.findElements(By.locatorType("path"));
    WebElement element = driver.findElement(By.locatorType("path"));
    List<WebElement> elements = element.findElements(By.locatorType("path"));

Some of the useful tasks that you can perform with the help of these functions are as follows:

  • Store Length: The following code snippet captures the list of textboxes available in a Google authentication page:
    driver.get("https://accounts.google.com/");
    List<WebElement> Textbox =driver.findElements(By.xpath("//script[@type='text/javascript']"));
    System.out.println("Overall textboxes:"+Textbox.size());
  • Click Element: Let's go through a book search on clicking on any one of the available autosuggestions. Fortunately, the first option from the list is chosen, which returns contents related to it as the search result. The following code snippet does the work for us:
    driver.get("http://www.indiabookstore.net");
    driver.findElement(By.id("searchBox")).sendKeys("Alche");
    List <WebElement> listItems = driver.findElements(By.xpath("//div[3]/ul/li"));
    listItems.get(0).click();
  • Locate by tag name: Capturing elements using tag names is widely used to collect autosuggestions, checkboxes, ordered lists, and so on. The following snippet is an example for capturing elements through the tagName function:
    List<WebElement> link = driver.findElement(By.locatorType("path")).findElements(By.tagName("li"));
  • Multi-select elements: This snippet gives you a clear idea on how to use the multi-select functionality. Here, the findElements() method is used to return the total length of the option tag, and it lets you pick all the preferred checkboxes:
    driver.get("http://www.ryancramer.com/journal/entries/select_multiple/");
    List<WebElement> ele = driver.findElements(By.tagName("select"));
    System.out.println(ele.size());
    WebElement ele2 = ele.get(0);
    List<WebElement> ele3 = ele2.findElements(By.tagName("option"));
    System.out.println(ele3.size());
    ele2.sendKeys(Keys.CONTROL);
    ele3.get(0).click();
    ele3.get(1).click();
    ele3.get(3).click();
    ele3.get(4).click();
    ele3.get(5).click();
  • Capture and navigate all links in a web page: As discussed in the preceding section, the element list is captured and stored in a single dimensional array using the findElements() method. Later, the user is intended to navigate each and every link one by one. The following snippet is an example for capturing and navigating all links in a web page:
    private static String[] links = null;
    private static int linksCount = 0;
    driver.get("https://www.google.co.in");
    List<WebElement> linksize = driver.findElements(By.tagName("a")); 
    linksCount = linksize.size();
    System.out.println("Total no of links Available: "+linksCount);
    links= new String[linksCount];
    System.out.println("List of links Available: ");  
    // print all the links from webpage 
    for(int i=0;i<linksCount;i++)
    {
      links[i] = linksize.get(i).getAttribute("href");
    } 
    // navigate to each Link on the webpage
    for(int i=0;i<linksCount;i++)
    {
      driver.navigate().to(links[i]);
      Thread.sleep(3000);
    }
  • Capture all links under specific frame/class/ID and navigate one by one: In general, StaleElementException will be thrown whenever a user navigates through the link and tries to click on the second link after returning from the visited page. To avoid such exceptions, an external method, getElementWithIndex(), is used to return values. The following code snippet exemplifies this method:
    driver.get("https://www.google.co.in");
    WebElement element = driver.findElement(By.locatorType("path"));
    List<WebElement> elements = element.findElements(By.tagName("a"));
    int sizeOfAllLinks = elements.size();
    System.out.println(sizeOfAllLinks);
    for(int i=0; i<sizeOfAllLinks ;i++)
    {
      System.out.println(elements.get(i).getAttribute("href"));
    }
    for (int index=0; index<sizeOfAllLinks; index++ ) {
      getElementWithIndex(By.tagName("a"), index).click();
      driver.navigate().back();
    }
    
    public WebElement getElementWithIndex(By by, int index) {
      WebElement element = driver.findElement(By.id(Value));
      List<WebElement> elements = element.findElements(By.tagName("a")); 
      return elements.get(index);
    }
  • Capture all links: The following model follows looping conditions to capture all the links present in a web page:
    driver.get("https://www.google.co.in");
    List<WebElement> all_links_webpage = driver.findElements(By.tagName("a")); 
    System.out.println("Total no of links Available: " + all_links_webpage.size());
    int k = all_links_webpage.size();
    System.out.println("List of links Available: ");
    for(int i=0;i<k;i++)
    {
      if(all_links_webpage.get(i).getAttribute("href") .contains("google"))
      {
        String link = all_links_webpage.get(i).getAttribute("href");
        System.out.println(link);
      }
    }
  • Locate and select autocomplete: The following snippet captures and clicks on a list of autocomplete results grown at runtime using the list <li> tag:
    driver.get("http://www.indiabookstore.net");
    driver.findElement(By.id("searchBox")).sendKeys("Alche");
    Thread.sleep(3000);
    List <WebElement> listItems = driver.findElements(By.cssSelector(".acResults li"));
    listItems.get(0).click();
    driver.findElement(By.id("searchButton")).click();
  • Store autosuggestions using iterator: The iterator is an alternative method to handle loops. In this example, a list of autosuggestions is iterated and stored:
    driver.get("http://www.indiabookstore.net/");
    driver.findElement(By.id("searchBox")).sendKeys("sam"); 
    WebElement table = driver.findElement(By.className("acResults"));
    List<WebElement> rowlist = table.findElements(By.tagName("li"));
    System.out.println("Total No. of list: "+rowlist.size());
    Iterator<WebElement> i = rowlist.iterator();
    System.out.println("Storing Auto-suggest..........");
    while(i.hasNext())
    {
      WebElement element = i.next();
      System.out.println(element.getText());
    }
  • The looping iteration can also be wrapped with the following snippet. It is as simple as the preceding snippet. Here, the list items are declared to a variable named called temp. Through temp, the values are being retrieved:
    List<WebElement> listitems = driver.findElements(By.id("value"));
    for(WebElement temp: listitems) // temp is the declared variable name
    {
      System.out.println((temp.findElement(By.tagName("value")).getText()));
    }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.167