Validate particular link on Web Page using Selenium Web Driver (Java)

  • Given any web page, we would like to validate the particular link on a web page .
  • We will use Selenium Web driver using Java binding language.
  • We would following the trailing steps for validation of a particular link:
    • We would like to find all the links on a webpage using findElements() function.
      • “driver.findElements(By.tagName(“a”)).size()” will give us the count of number of links on particular web page.
    • We can open link in a new tab by pressing control and enter key at the same time
      Keys.chord(Keys.CONTROL, Keys.ENTER).
    • driver. getWindowHandles() return a set of window handles and is mainly used to get the window handle of all the current windows.
    • We could switch to a particular window using:
      driver.switchTo().window() and validate the url/title.

Code: Validate the particular link on the Web Page using Selenium WebDriver

package org.learn;

import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Random {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.setProperty("webdriver.chrome.driver", "C:\\\\work\\\\chromedriver.exe");
		WebDriver driver = new ChromeDriver();
		driver.get("https:www.gmail.com");
		// Give count of number of links on page
		int numberOfLinks = driver.findElements(By.tagName("a")).size();
		System.out.println("Number of links on Web Page :" + numberOfLinks);

		// Click on all the links to open them in a new tab
		for (int i = 0; i < numberOfLinks; i++) {
			String clickOnClick = Keys.chord(Keys.CONTROL, Keys.ENTER);
			driver.findElements(By.tagName("a")).get(i).sendKeys(clickOnClick);
		}
		
		//To validate the url or title of particular link
		Set ids = driver.getWindowHandles();
		Iterator<String> it = ids.iterator();
		while (it.hasNext()) {
			driver.switchTo().window(it.next());
			System.out.println(driver.getTitle());
			//System.out.println(driver.getCurrentUrl());
		}

	}
}

Output – Validate the title/url of particular link on the Web Page using Selenium

Gmail
Google Terms of Service – Privacy & Terms – Google
Privacy Policy – Privacy & Terms – Google
Google Account Help
Browse Chrome as a guest - Computer - Google Chrome Help
Scroll to Top