Saturday 28 February 2015

Accessing Multiple Links in the Web Page

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 com.company;

import org.openqa.selenium.By;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class AllLinks {


    public static void main(String[] args) {
        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();
    }
}

--------------------------------------------------------------------------------------------------------------------------------
 

Select Language