how fetch all links and click those licks one by one using selenium webdriver

11,930 views
Skip to first unread message

shammi

unread,
Nov 19, 2012, 12:29:04 AM11/19/12
to seleniu...@googlegroups.com

I m using selenuim webdriver, lang: java

I am fetching all links from webpage and trying to click each link one by one.

1)  I am getting below error: error org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up Command duration or timeout: 30.01 seconds For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html Build info: version: '2.25.0', revision: '17482', time: '2012-07-18 21:09:54'

2)  it's displaying in output "[[FirefoxDriver: firefox on XP (ce0da229-f77b-4fb8-b017-df517845fa78)] -> tag name: a]" as link, I want to eliminate these form result

and here is my code : public void getLinks()throws Exception{

 try { 

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

int linkcount = links.size(); 

System.out.println(links.size());

 for (WebElement myElement : links){ 

String link = myElement.getText();

 System.out.println(link); System.out.println(myElement);
if (link !=""){

 myElement.click(); Thread.sleep(2000); System.out.println("third"); 

} //Thread.sleep(5000); 

} }

catch (Exception e){

 System.out.println("error "+e); } }

 Please help

Nitin Rajpal

unread,
Nov 19, 2012, 12:33:24 AM11/19/12
to seleniu...@googlegroups.com
Try this

List<WebElement> componentList = driver.findElements(By.linkText("a"));
for (WebElement component : componentList)
{
   if (component.getAttribute("onclick/href/value").contains("urchoice"))
   {
       component.click();
       break;

shammi

unread,
Nov 19, 2012, 4:19:07 AM11/19/12
to seleniu...@googlegroups.com
Hi Nitin,
               Thanks for for your reply.
But still I am getting same error, loop is running once and next time it's throwing error. If we put break in the end of if condition then loop is running only once.

try {
List<WebElement> componentList = driver.findElements(By.tagName("a"));
System.out.println(componentList.size()); 
 
for (WebElement component : componentList)
{System.out.println(component.getAttribute("href"));
   if (component.getAttribute("href").contains("http://www.google.com/"))
   {
    String link = component.getText(); 
System.out.println(link);
System.out.println(component);
     
       component.click();
       System.out.println("clicked");
      // break;

Mark Collin

unread,
Nov 19, 2012, 4:59:35 PM11/19/12
to seleniu...@googlegroups.com

You are getting a stale element exception because the DOM has changed after you have clicked a link (either because you have been navigated to a new page or reloaded the DOM on the old page).

 

You would need to re-find the element after each click to eliminate the stale element exception.

 

What are you trying to do?

--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/FWmpT5GuxksJ.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Mark Collin

unread,
Nov 20, 2012, 1:35:20 AM11/20/12
to seleniu...@googlegroups.com

Maybe I’m not being clear, why do you want to click each link?  Do you just want to check the link isn’t dead?

 

If so something like this would be easier:

 

https://github.com/Ardesco/Powder-Monkey/tree/master/src/main/java/com/lazerycode/selenium/urlstatuschecker

 

It’s explained on this blog entry:

 

http://ardesco.lazerycode.com/index.php/2012/07/how-to-download-files-with-selenium-and-why-you-shouldnt/

 

 

From: seleniu...@googlegroups.com [mailto:seleniu...@googlegroups.com] On Behalf Of shami
Sent: 20 November 2012 04:45
To: seleniu...@googlegroups.com
Subject: Re: [selenium-users] Re: how fetch all links and click those licks one by one using selenium webdriver

 

1) I want to fetch and display all links on webpage.

2) after displaying, I am want to click each link one by one.

To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/A-jCBRUcZa0J.

Alex

unread,
Nov 20, 2012, 6:15:41 AM11/20/12
to seleniu...@googlegroups.com
i just came here to see how one clicks a lick

shammi

unread,
Nov 26, 2012, 8:13:42 AM11/26/12
to seleniu...@googlegroups.com
Finally I got it, here we go : 

public void getLinks()throws Exception{
try {
List<WebElement> componentList = driver.findElements(By.tagName("a"));
 int numberOfElementsFound = getNumberOfElementsFound(By.tagName("a"));
 for (int pos = 0; pos < numberOfElementsFound; pos++) {
 if (getElementWithIndex(By.tagName("a"), pos).isDisplayed()){
 getElementWithIndex(By.tagName("a"), pos).click();
 }
 }

Gaurab Pradhan

unread,
Dec 20, 2013, 10:34:50 AM12/20/13
to seleniu...@googlegroups.com
Dear Shammi,
I am also facing same as yours,
I have used your code but it shows error on
 if (getElementWithIndex(By.tagName("a"), pos).isDisplayed()){ // it shows error in isDisplayed
 getElementWithIndex(By.tagName("a"), pos).click();  // it shows error in click() method

I am new programmer can you give detail example?? 

Shammi Kapoor

unread,
Dec 23, 2013, 4:14:43 AM12/23/13
to seleniu...@googlegroups.com
Hi Gaurab,
               You have to define getNumberOfElementsFound() and getElementWithIndex() methods.

public int getNumberOfElementsFound(By by) {
        return  driver.findElements(by).size();
      }
     
    public WebElement getElementWithIndex(By by, int pos) {
            return driver.findElements(by).get(pos);
          }



You received this message because you are subscribed to a topic in the Google Groups "Selenium Users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/selenium-users/Gmw3Zsq0-Gg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to selenium-user...@googlegroups.com.

To post to this group, send email to seleniu...@googlegroups.com.

For more options, visit https://groups.google.com/groups/opt_out.



--
Thanks & Regards
Shammi Kapoor
(9742413762)

Gaurab Pradhan

unread,
Dec 23, 2013, 11:33:52 PM12/23/13
to seleniu...@googlegroups.com

Dear Shammi,
Thanks a lot....

Diya Sharma

unread,
Jan 26, 2014, 3:32:42 PM1/26/14
to seleniu...@googlegroups.com
Hi Shammi,

I saw your post and tried the code:
1) To get all the links of a web page and click them one by one.
I am using Selenium Webdriver.

 Its working for me but i am getting java.lang.IndexOutOfBoundsException error after the loop is executed 11 times.

Code :

import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class links1 {

    private WebDriver driver1;
    String siteURL = "https://www.elitmus.com";

    @Before
    public void getLinks1() throws Exception {
        driver1 = new FirefoxDriver();
        driver1.get(siteURL);
    }

    @Test
    public void getLinks() throws Exception {

        try {

            List<WebElement> componentList = driver1.findElements(By

                    .tagName("a"));

            int numberOfElementsFound = getNumberOfElementsFound(By
                    .tagName("a"));
            System.out.println(numberOfElementsFound);


           

            for (int pos = 0; pos < numberOfElementsFound; pos++) {

                if (getElementWithIndex(By.tagName("a"), pos).isDisplayed()) {

                    getElementWithIndex(By.tagName("a"), pos).click();
                    System.out.println("pass");
                    System.out.println(pos);

                } else {
                    System.out.println("fail");
                    System.out.println(pos);
                }

            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getNumberOfElementsFound(By by) {
        return driver1.findElements(by).size();

    }

    public WebElement getElementWithIndex(By by, int pos) {
        return driver1.findElements(by).get((int) pos);
    }
}

Output :

 39
pass
0
pass
1
pass
2
pass
3
pass
4
pass
5
pass
6
pass
7
pass
8
fail
9
pass
10
pass
11
java.lang.IndexOutOfBoundsException: Index: 12, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at abc.links1.getElementWithIndex(links1.java:63)
    at abc.links1.getLinks(links1.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Panikera Raj

unread,
Jan 27, 2014, 7:36:58 AM1/27/14
to seleniu...@googlegroups.com
Hi Diya Sharma,
 
While iterating loop you have to use for loop as :
 
for (int pos = 0; pos < numberOfElementsFound -1; pos++) {
 
instead of
 
for (int pos = 0; pos < numberOfElementsFound; pos++) {
 
Regards,
Panikera
 

--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to selenium-user...@googlegroups.com.

To post to this group, send email to seleniu...@googlegroups.com.

sk.sele...@gmail.com

unread,
Mar 31, 2019, 10:23:00 AM3/31/19
to Selenium Users
Hi Frnds,

How to get all links and click on specific link on webpage.

Ex: i need to click on 15th link to 20th link only. please help me frnds.

Karthik Deepan

unread,
Mar 31, 2019, 10:40:31 AM3/31/19
to seleniu...@googlegroups.com

This method will you all links added in a given list -->

List<WebElements> allLinks = driver.findElements(By.tagName("a"));

then you can use, allLinks.get(14).click(); to click on the 15th element.

Once you click the link, the webPage will direct to you to the clicked link



--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to selenium-user...@googlegroups.com.
To post to this group, send email to seleniu...@googlegroups.com.

Suresh Chaudhry

unread,
Apr 1, 2019, 3:51:41 AM4/1/19
to seleniu...@googlegroups.com
Hi frnds,

but i need to click on 15 link to 20th links 

Joe Ward

unread,
Apr 1, 2019, 4:37:04 AM4/1/19
to seleniu...@googlegroups.com
The above answer works regardless of the number of entries in the list.

That being said, maybe something like http://home.snafu.de/tilman/xenulink.html would be more helpful to you than Selenium? Depends on what exactly you want to do and why.

spqual...@gmail.com

unread,
Apr 1, 2019, 4:47:16 AM4/1/19
to Selenium Users
Thanks Kartik,

But I need to click on 15th links to 20th links.

Suresh Chaudhry

unread,
Apr 1, 2019, 4:48:34 AM4/1/19
to seleniu...@googlegroups.com
Hi,

I have webpages in that webpages I need to click specific links only.

Ex: 10 links are there in 1st webpage.

I need to click 5th link upto 9th links.

Joe Ward

unread,
Apr 1, 2019, 4:50:37 AM4/1/19
to seleniu...@googlegroups.com

Suresh Chaudhry

unread,
Apr 1, 2019, 4:59:49 AM4/1/19
to seleniu...@googlegroups.com
I think it should be won't work I think so..

Karthik Deepan

unread,
Apr 1, 2019, 5:20:48 AM4/1/19
to seleniu...@googlegroups.com
What will happen when you click 15th link?

 like     Will the webpage navigate to the new Link?
           Will there be a new window/Tab opened?
           What you want to do after opening those 5 links? What validation is required?

Suresh Chaudhry

unread,
Apr 1, 2019, 8:17:51 AM4/1/19
to seleniu...@googlegroups.com
Those links are working are not. Checking

Rahul Rai

unread,
Jan 5, 2022, 11:30:07 PM1/5/22
to Selenium Users
Hi Shammi,

I am stuck with this same query which i was testing for one of my project and i used your solution above but its not working after some loop count.
Actually my scenario is to find all the active links on a Homepage and then click one link and navigate to the new page and navigate back to home page and click on the next link from the Home Page active list of links.

Could you please share your though and also the code on how i can achieve this.
I am new to Java and I am not getting any solution for my this query anywhere.

Thank you,
Rahul
+8051204709

Reply all
Reply to author
Forward
0 new messages