usr999
usr999

Reputation: 156

Get link text - Selenium, Java

I'm trying to get all links from a web page. I tried to use

WebDriver driver = FirefoxDriver();
List<WebDriver> elements = driver.findElements(By.tagName("a"));

But I get zero links. How can I fix this?

I need to get the part from <a href="url">. I need the URL text.


I think found what I was looking for:

List<WebElement> elements = driver.findElements(By.tagName("a"));
for (int i = 0; i < elements.size(); i++) {
   System.out.println(elements.get(i).getAttribute("href"));
}

Upvotes: 3

Views: 13455

Answers (3)

Harshaaaa
Harshaaaa

Reputation: 3

I was facing same issue but now it resolved If you want to fetch all the links from the webpage you need to use List class and than use webelement

     List<WebElement> allLinks = driver.findElements(By.tagName("a"));
                      int linkcount=allLinks.size();
                      System.out.println("All Links :" +linkcount);
                 
                      for(int j=0 ;j<linkcount;j++)
                       {
                        String ele= driver.findElements(By.tagName("a")).get(j).getText();
                         
                        System.out.println(ele);
                    
                              
                       }

Upvotes: 0

Petr Mensik
Petr Mensik

Reputation: 27536

You forgot to call WebDriver#get in order to access some page.

WebDriver driver = FirefoxDriver();   
driver.get("www.google.com");
List<WebElement> elements = driver.findElements(By.tagName("a")); 

Upvotes: 4

Kevin Bowersox
Kevin Bowersox

Reputation: 94489

In the code provided no website is retrieved. Try accessing a web page and then getting the a elements. Also trying changing from List<WebDriver> to List<WebElement>

   WebDriver driver = FirefoxDriver();
   driver.get("http://www.google.com"); 
   List<WebElement> elements = driver.findElements(By.tagName("a")); 

See this example: http://www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example

The following example works for me:

 public class SeleniumTest {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");
        List<WebElement> elements = driver.findElements(By.tagName("a"));

        for (WebElement element : elements) {
            System.out.println(element.getText());
        }
    }
}

Upvotes: 2

Related Questions