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?

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

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.

  • It's giving an error at line HashSet – Sayali Joglekar May 3 '18 at 10:21
  • Which error are you getting? – Alexey R. May 3 '18 at 10:34
  • HashSet cannot be resolved to a type – Sayali Joglekar May 3 '18 at 10:36
  • Import it from java.util package – Alexey R. May 3 '18 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> – Sayali Joglekar May 3 '18 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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