Need to get all available links using WebDriver

11,554

Solution 1

You can get all links using below logic.

List<WebElement> link=driver.findElements(By.tagName("a"));

for(WebElement ele:link)
{
     System.out.println(ele.getText());
} 

Solution 2

    List<WebElement> list=driver.findElements(By.xpath("//a"));
    System.out.println("No of links present="+ list.size());

    // use of for loop for iteration
    for(int i=0;i<list.size();i++){
        System.out.println(list.get(i).getText());
    }
    System.out.println("-------------------------");
    //use of for each for iteration
    for(WebElement wb: list)
        System.out.println(wb.getText());

Solution 3

I agree with Max.Mirkia, to grab urls from 'href'

modified Santoshsarma code

 List<WebElement> tagName = driver.findElements(By.tagName("a"));
    for(WebElement ele:tagName)
    {
        String urls = ele.getAttribute("href");
        System.out.println(urls);
    }
}
Share:
11,554

Related videos on Youtube

AlienS
Author by

AlienS

Updated on September 15, 2022

Comments

  • AlienS
    AlienS over 1 year

    How to get all available links in a web page using WebDriver?

  • Max.Mirkia
    Max.Mirkia over 9 years
    I think you should call the "getAttribute" function on WebElement in the last line passing "href" as its argument