How can i get all the links of a webpage and click one by one using selenium

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

How can i get all the links of a webpage and click one by one using selenium

Ganesh
Hi All

How can i get all the links of a webpage and click one by one using selenium
   
//Code
WebDriver driver = new FirefoxDriver();
driver.get("http://www.HRS.com");
List<WebElement> MyList = driver.findElements(By.xpath("//a"));
for(WebElement Element : MyList)
 {
   Element.click();  ----> m getting an error (IN 2 ITERATION) stating
                           "Element not found in the cache - perhaps the page has changed since it was looked up"
                             
 }


Can any one help me out ?

Thanks in advance
Reply | Threaded
Open this post in threaded view
|

Re: How can i get all the links of a webpage and click one by one using selenium

softwaretestingforum
Administrator
Hi Ganesh,

The problem with this approach is that Webdriver looses reference to element objects as soon as  page is refresh or dom is changed because of some ajax activity. As soon as you do -

Ganesh wrote
   Element.click();  
Webdriver looses the reference of all the elements which you collected in MyList.
To over come this you can find the size of MyList and then iterator though anchor element using some index number. Which means that every time you would locating element again once you have performed a click like -

int linkCount = MyList.size()

for(int i=1; i<linkCount;i++){
driver.findElements(By.xpath("//a"+i+"")).click()
}</i>


Your original mechanism of locating element would differ but I hope you get the idea.

 
~ seleniumtests.com
Reply | Threaded
Open this post in threaded view
|

Re: How can i get all the links of a webpage and click one by one using selenium

Ganesh
Hi Tarun,

I have tried u r method by fetching the size and iterating element using the index value

//Code
public static void main(String args[])throws Exception
    {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.hrs.com");
    List<WebElement> MyList = driver.findElements(By.xpath("//a"));
        int linkcount =MyList.size();
        System.out.println(linkcount); ----------> o/p : 104
        for (int i=1;i<linkcount;i++)
        {
        driver.findElement(By.xpath("//a['"+i+"']")).click();   -> same url (www.hrs.com is loaded for 104 times )
        }  
     }

Problem i face here is, link count is 104, For each iteration it loads the same page( i.e www.hrs.com is loaded for 104 times)

Thanks
ganesh
Reply | Threaded
Open this post in threaded view
|

Re: How can i get all the links of a webpage and click one by one using selenium

softwaretestingforum
Administrator
I suppose you need to fix this -

driver.findElement(By.xpath("//a['"+i+"']"))

to match your application. Looks like a[1], a[2] etc all are referring to same links.
~ seleniumtests.com