Akshay K Sharma
Akshay K Sharma

Reputation: 1

How to get all the links present in the web page which uses java script

I am using selenium web driver to fetch all the links present using the following logic:

public static List findAllLinks(WebDriver driver)
{
    List elementList = new ArrayList();
    elementList = driver.findElements(By.tagName("a"));

    elementList.addAll(driver.findElements(By.tagName("img")));

    List finalList = new ArrayList(); ;

    for (WebElement element : elementList)
    {
        if(element.getAttribute("href") != null)
        {
            finalList.add(element);
        }         
    }   

    return finalList;
}

but it only returns links starting with http and not which are there by java script.how can I get those links?

Upvotes: 0

Views: 1047

Answers (1)

Shashank Shah
Shashank Shah

Reputation: 2167

You may use getElementsByTagName.

var links = document.getElementsByTagName('a');
for(var i = 0; i< links.length; i++){
  alert(links[i].href);
}

Another way would be document.links to get anchortags loop it and get href!

var linkArray = [], links = document.links;
for(var i=0; i<links.length; i++) {
  linkArray.push(links[i].href);
  alert(links[i].href);
}

now you have array of all the href attributes from the anchors in the page!

Hope it helps! :)

Upvotes: 4

Related Questions