In this tutorial, we are going to learn about accessing links & Tables using Webdriver

Part 1) Accessing Links

Links Matching a Criterion

Links can be accessed using an exact or partial match of their link text. The examples below provide scenarios where multiple matches would exist and would explain how WebDriver would deal with them.

Exact Match

Accessing links using their exact link text is done through the By.linkText() method. However, if there are two links that have the very same link text, this method will only access the first one. Consider the HTML code below

Accessing Links & Web Tables using Selenium Webdriver

Accessing Links & Web Tables using Selenium Webdriver

 

When you try to run the WebDriver code below, you will be accessing the first "click here" link

.Accessing Links & Web Tables using Selenium Webdriver

 

As a result, you will automatically be taken to Google.

Accessing Links & Web Tables using Selenium Webdriver

 

Partial Match

Accessing links using a portion of their link text is done using the By.partialLinkText() method. If you specify a partial link text that has multiple matches, only the first match will be accessed. Consider the HTML code below.

Accessing Links & Web Tables using Selenium Webdriver

Accessing Links & Web Tables using Selenium Webdriver

When you execute the WebDriver code below, you will still be taken to Google.

Accessing Links & Web Tables using Selenium Webdriver

Accessing Links & Web Tables using Selenium Webdriver

Case-sensitivity

The parameters for By.linkText() and By.partialLinkText() are both case-sensitive, meaning that capitalization matters. For example, in Mercury Tours' homepage, there are two links that contain the text "egis" - one is the "REGISTER" link found at the top menu, and the other is the "Register here" link found at the lower right portion of the page.

Accessing Links & Web Tables using Selenium Webdriver

Though both links contain the character sequence "egis," the 0"By.partialLinkText()" method will access these two links separately depending on the capitalization of the characters. See the sample code below.

Accessing Links & Web Tables using Selenium Webdriver

All Links

One of the common procedures in web Testing is to test if all the links present within the page are working. This can be conveniently done using a combination of the Java for-each loop and the By.tagName("a") method. The WebDriver code below checks each link from the Mercury Tours homepage to determine those that are working and those that are still under construction.

package newproject;

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class PG5 
{
	 public static void main(String[] args) {
		 	System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
	        String baseUrl = "http://newtours.demoaut.com/";
	        WebDriver driver = new FirefoxDriver();
	        String underConsTitle = "Under Construction: Mercury Tours";
	        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

	        driver.get(baseUrl);
	        List<WebElement> linkElements = driver.findElements(By.tagName("a"));
	        String[] linkTexts = new String[linkElements.size()];
	        int i = 0;

	        //extract the link texts of each link element
	        for (WebElement e : linkElements) {
	            linkTexts[i] = e.getText();
	            i++;
	        }

	        //test each link
	        for (String t : linkTexts) {
	            driver.findElement(By.linkText(t)).click();
	            if (driver.getTitle().equals(underConsTitle)) {
	                System.out.println("\"" + t + "\""
	                        + " is under construction.");
	            } else {
	                System.out.println("\"" + t + "\""
	                        + " is working.");
	            }
	            driver.navigate().back();
	        }
	        driver.quit();

	    }
}

The output should be similar to the one indicated below.

Accessing Links & Web Tables using Selenium Webdriver

Links Outside and Inside a Block

The latest HTML5 standard allows the <a> tags to be placed inside and outside of block-level tags like <div>, <p>, or <h1>. The "By.linkText()" and "By.partialLinkText()" methods can access a link located outside and inside these block-level elements. Consider the HTML code below.

Accessing Links & Web Tables using Selenium Webdriver

Accessing Links & Web Tables using Selenium Webdriver

The WebDriver code below accesses both of these links using By.partialLinkText() method.

Accessing Links & Web Tables using Selenium Webdriver

The output above confirms that both links were accessed successfully because their respective page titles were retrieved correctly.

Accessing Image Links

Image links are images that act as references to other sites or sections within the same page. Since they are images, we cannot use the By.linkText() and By.partialLinkText() methods because image links basically have no link texts at all. In this case, we should resort to using either By.cssSelector or By.xpath. The first method is more preferred because of its simplicity.

In the example below, we will access the "Facebook" logo on the upper left portion of Facebook's Password Recovery page.

Accessing Links & Web Tables using Selenium Webdriver

 

We will use By.cssSelector and the element's "title" attribute to access the image link. And then we will verify if we are taken to Facebook's homepage.

package newproject;

import org.openqa.selenium.*;
//import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class PG6 {

	public static void main(String[] args) {
        String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";
        System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();

        driver.get(baseUrl);
        //click on the "Facebook" logo on the upper left portion
        driver.findElement(By.cssSelector("a[title=\"Go to Facebook home\"]")).click();

        //verify that we are now back on Facebook's homepage
        if (driver.getTitle().equals("Facebook - Log In or Sign Up")) {
            System.out.println("We are back at Facebook's homepage");
        } else {
            System.out.println("We are NOT in Facebook's homepage");
        }
        driver.close();
    }
}

Result

Accessing Links & Web Tables using Selenium Webdriver

 

Part 2) Reading a Table

There are times when we need to access elements (usually texts) that are within HTML tables. However, it is very seldom for a web designer to provide an id or name attribute to a certain cell in the table. Therefore, we cannot use the usual methods such as "By.id()", "By.name()", or "By.cssSelector()". In this case, the most reliable option is to access them using the "By.xpath()" method.

XPath Syntax

Consider the HTML code below.

Accessing Links & Web Tables using Selenium Webdriver

We will use XPath to get the inner text of the cell containing the text "fourth cell." 

Accessing Links & Web Tables using Selenium Webdriver

Step 1 - Set the Parent Element (table)

XPath locators in WebDriver always start with a double forward slash "//" and then followed by the parent element. Since we are dealing with tables, the parent element should always be the <table> tag. The first portion of our XPath locator should, therefore, start with "//table".

Accessing Links & Web Tables using Selenium Webdriver

Step 2 - Add the child elements

The element immediately under <table> is <tbody> so we can say that <tbody> is the "child" of <table>. And also, <table> is the "parent" of <tbody>. All child elements in XPath are placed to the right of their parent element, separated with one forward slash "/" like the code shown below.

Accessing Links & Web Tables using Selenium Webdriver                                  Accessing Links & Web Tables using Selenium Webdriver

Step 3 - Add Predicates

The <tbody> element contains two <tr> tags. We can now say that these two <tr> tags are "children" of <tbody>. Consequently, we can say that <tbody> is the parent of both the <tr> elements.

Another thing we can conclude is that the two <tr> elements are siblings. Siblings refer to child elements having the same parent.

To get to the <td> we wish to access (the one with the text "fourth cell"), we must first access the second <tr> and not the first. If we simply write "//table/tbody/tr", then we will be accessing the first <tr> tag.

So, how do we access the second <tr> then? The answer to this is to use Predicates.

Predicates are numbers or HTML attributes enclosed in a pair of square brackets "[ ]" that distinguish a child element from its siblings. Since the <tr> we need to access is the second one, we shall use "[2]" as the predicate.

Accessing Links & Web Tables using Selenium Webdriver

If we won't use any predicate, XPath will access the first sibling. Therefore, we can access the first <tr> using either of these XPath codes.

Accessing Links & Web Tables using Selenium Webdriver

Step 4 - Add the Succeeding Child Elements Using the Appropriate Predicates

The next element we need to access is the second <td>. Applying the principles we have learned from steps 2 and 3, we will finalize our XPath code to be like the one shown below.

Accessing Links & Web Tables using Selenium Webdriver

Now that we have the correct XPath locator, we can already access the cell that we wanted to and obtain its inner text using the code below. It assumes that you have saved the HTML code above as "newhtml.html" within your C Drive.

Accessing Links & Web Tables using Selenium Webdriver

Accessing Links & Web Tables using Selenium Webdriver

 

Accessing Nested Tables

The same principles discussed above applies to nested tables. Nested tables are tables located within another table. An example is shown below.

Accessing Links & Web Tables using Selenium WebdriverAccessing Links & Web Tables using Selenium Webdriver

To access the cell with the text "4-5-6" using the "//parent/child" and predicate concepts from the previous section, we should be able to come up with the XPath code below.

Accessing Links & Web Tables using Selenium Webdriver

 

The WebDriver code below should be able to retrieve the inner text of the cell which we are accessing.

Accessing Links & Web Tables using Selenium Webdriver

The output below confirms that the inner table was successfully accessed.

Accessing Links & Web Tables using Selenium Webdriver

Using Attributes as Predicates

If the element is written deep within the HTML code such that the number to use for the predicate is very difficult to determine, we can use that element's unique attribute instead.

In the example below, the "New York to Chicago" cell is located deep into Mercury Tours homepage's HTML code.

Accessing Links & Web Tables using Selenium Webdriver

Accessing Links & Web Tables using Selenium Webdriver

 

In this case, we can use the table's unique attribute (width="270") as the predicate. Attributes are used as predicates by prefixing them with the @ symbol. In the example above, the "New York to Chicago" cell is located in the first <td> of the fourth <tr>, and so our XPath should be as shown below.

Accessing Links & Web Tables using Selenium Webdriver

Remember that when we put the XPath code in Java, we should use the escape character backward slash "\" for the double quotation marks on both sides of "270" so that the string argument of By.xpath() will not be terminated prematurely.

Accessing Links & Web Tables using Selenium Webdriver

We are now ready to access that cell using the code below.

Accessing Links & Web Tables using Selenium Webdriver

Accessing Links & Web Tables using Selenium Webdriver

 

Shortcut: Use Firebug for Accessing Tables in Selenium

If the number or attribute of an element is extremely difficult or impossible to obtain, the quickest way to generate the XPath code is thru Firebug.

Consider the example below from Mercury Tours homepage.

Accessing Links & Web Tables using Selenium Webdriver

Step 1

Use Firebug to obtain the XPath code.

Accessing Links & Web Tables using Selenium Webdriver

 

Step 2

Look for the first "table" parent element and delete everything to the left of it.

Accessing Links & Web Tables using Selenium Webdriver

Step 3

Prefix the remaining portion of the code with double forward slash "//" and copy it over to your WebDriver code.

Accessing Links & Web Tables using Selenium Webdriver

The WebDriver code below will be able to successfully retrieve the inner text of the element we are accessing.

Accessing Links & Web Tables using Selenium Webdriver

Summary

  • Accessing links using their exact match is done using By.linkText() method.
  • Accessing links using their partial match is done using By.partialLinkText() method.
  • If there are multiple matches, By.linkText() and By.partialLinkText() will only select the first match.
  • Pattern matching using By.linkText() and By.partialLinkText() is case-sensitive.
  • The By.tagName("a") method is used to fetch all links within a page.
  • Links can be accessed by the By.linkText() and By.partialLinkText() whether they are inside or outside block-level elements.
  • Accessing image links are done using By.cssSelector() and By.xpath() methods.
  • By.xpath() is commonly used to access table elements.