In this article, I am going to explain to you how to find all anchor links on the page, I am using find element by tag name locator to find out all anchor elements
We are going to fetch all elements which the tag name equals to HTML element anchor tag, something like below, it returns a list of anchor links so, we must use List collection, once we have a list of links iterate it using for loop and print on the console
1 |
List<WebElement> links = driver.findElements(By.tagName("a")); |
Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.wr.aem.workflows; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public class LinksTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://www.keysandstrokes.info/"); List<WebElement> links = driver.findElements(By.tagName("a")); for (WebElement link : links) { System.out.println(link.getText()); System.out.println(link.getAttribute("href")); } driver.manage().window().maximize(); } } |
Output :