All Links can be accessed using an exact or partial match of their link text.
The scenarios where multiple matches would exist, and would explain how WebDriver would deal with all Links .
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. Tthe Mercury Tours homepage to determine those that are working and those that are still under construction.
package dayOne;
import java.util.List; import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TestLinks {
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();
}
}
Result :