Abhilash T
Abhilash T

Reputation: 13

How to fetch all links and click those links one by one with Selenium WebDriver

I want to do the following:

  1. I want to fetch and display all links on webpage.
  2. After displaying, I want to click each link one by one.

I'm able to do point 1 using foreach loop but I'm not able to 2nd point.

Here is the code:

public class OpenAllLinks {
    public static void main(String[] args) {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://bing.com");
        List<WebElement> demovar = driver.findElements(By.tagName("a"));
        System.out.println(demovar.size());

        for (WebElement var : demovar) {
            System.out.println(var.getText()); // used to get text present between the anchor tags
            System.out.println(var.getAttribute("href"));
        }

        for (WebElement var : demovar) {
            var.click();
        }
    }
}

Upvotes: 1

Views: 7100

Answers (3)

Manjeet Singh
Manjeet Singh

Reputation: 11

static WebDriver driver=null;
public static void main(String[] args) throws IOException 
{     System.setProperty("webdriver.chrome.driver","D:\\softwaretesting\\broswer driver\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();``
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        //driver.manage().window().maximize();
        driver.get("http://google.com/");      
        List<WebElement> links=driver.findElements(By.tagName("a"));            
        System.out.println("Total links are "+links.size());            
        for(int i=0;i<links.size();i++)
        {       
            WebElement ele= links.get(i);               
            String url=ele.getAttribute("href");                
            verifyLinkActive(url);          
        }        
    }       
    public static void verifyLinkActive(String linkUrl)
    {           try 
        {
           URL url = new URL(linkUrl);             
           HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();               
           httpURLConnect.setConnectTimeout(3000);             
           httpURLConnect.connect();               
           if(httpURLConnect.getResponseCode()==200)               {
               System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
               File src= (TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);     
               FileUtils.copyFile(src, new File("D://screenshort//Spiritualbridge//"+System.currentTimeMillis()+".png"));   
            }             if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)  
           {
               System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage() + " - "+ HttpURLConnection.HTTP_NOT_FOUND);
            }                
        }           catch (Exception e) 
        {              
        }       
    }   

Upvotes: 1

Subh
Subh

Reputation: 4424

That happens because the link when clicked, navigates to a new page where it doesn't find the next element in your list to click. Please try the below code that will navigate to each link (I have used the code by @deepak above and have modified it accordingly as per your need):

 WebDriver driver=new FirefoxDriver();

 driver.manage().window().maximize();

 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

 driver.get("http://bing.com");

 List<WebElement> demovar=driver.findElements(By.tagName("a"));
 System.out.println(demovar.size());

 ArrayList<String> hrefs = new ArrayList<String>(); //List for storing all href values for 'a' tag

    for (WebElement var : demovar) {
        System.out.println(var.getText()); // used to get text present between the anchor tags
        System.out.println(var.getAttribute("href"));
        hrefs.add(var.getAttribute("href")); 
        System.out.println("*************************************");
    }

    //Navigating to each link
    int i=0;
    for (String href : hrefs) {
        driver.navigate().to(href);
        System.out.println((++i)+": navigated to URL with href: "+href);
        Thread.sleep(3000); // To check if the navigation is happening properly.
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    }

Upvotes: 0

deepak
deepak

Reputation: 3172

when the first link is clicked, the browser will load the respective page. hence the other links those you had captured in the first page wouldn't be available.

If the intent is to navigate to the every link's target, then store the target location and navigate to it, like this

driver.get("<some site>");
List<WebElement> links=driver.findElements(By.tagName("a"))
ArrayList<String> targets = new ArrayList<String>();
//collect targets locations
for (WebElement link : links) {
     targets.add(link.getAttribute("href"));
}
for (WebElement target : targets) {
     driver.get(target);
     //do what is needed in the target
}

Upvotes: 2

Related Questions