0
public class Test1 {
    public static void main(String[] args) {

        // Storing Url in the String variable
        String url = "Target URL ";
        // Launch
        driver.get(url);
        // List Of URL
        List<WebElement> links = driver.findElements(By.tagName("a"));
        System.out.println("Total Count:" + links.size());
        Iterator<WebElement> it = links.iterator();
        while (it.hasNext()) {
            url = it.next().getAttribute("href");

            System.out.println(url);

        }

    }
}

How to scroll to the particular single URL and click it using selenium?

4
  • use the bobble sorting method
    – Vel Guru
    May 3, 2018 at 9:34
  • wanted to avoid repeated URL . May 3, 2018 at 9:40
  • What's your goal here? Are you trying to validate that there's no broken links?
    – Florent B.
    May 3, 2018 at 14:26
  • Trying to fetch Distinct URL May 4, 2018 at 6:27

1 Answer 1

1

Create a HashSet<String> and put all your URLs there. After you have added the last URL you will be having only unique set in your HashSet.

import java.util.*;
// .. some other imports here
public static void main(String[] args) {
    // Storing Url in the String variable
    String url = "Target URL ";
    // Launch
    driver.get(url);
    // List Of URL
    List<WebElement> links = driver.findElements(By.tagName("a"));
    System.out.println("Total Count:" + links.size());
    // Create hashset
    HashSet<String> uniqueURLs = new HashSet<String>();
    // Add all your elements to hashset
    for(WebElement link: links){
        uniqueURLs.add(link.getAttribute("href"));
    }
    for (String urlUniqueItem: new ArrayList<String>(uniqueURLs)) {
        System.out.println(urlUniqueItem);
    }
}

HashSet do not store object duplicates so that you can be sure after you have added all the objects there would no be duplicates.

12
  • It's giving an error at line HashSet May 3, 2018 at 10:21
  • Which error are you getting?
    – Alexey R.
    May 3, 2018 at 10:34
  • HashSet cannot be resolved to a type May 3, 2018 at 10:36
  • Import it from java.util package
    – Alexey R.
    May 3, 2018 at 10:40
  • uniqueURLs.add(link.getAttribute("href"));Exception in thread "main" java.lang.Error: Unresolved compilation problems: The method add(String) is undefined for the type HashSet<String> The method iterator() is undefined for the type HashSet<String> May 3, 2018 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.