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?

Kate Paulk
31.5k8 gold badges56 silver badges109 bronze badges
asked May 3, 2018 at 9:31
4
  • use the bobble sorting method Commented May 3, 2018 at 9:34
  • wanted to avoid repeated URL . Commented May 3, 2018 at 9:40
  • What's your goal here? Are you trying to validate that there's no broken links? Commented May 3, 2018 at 14:26
  • Trying to fetch Distinct URL Commented 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.

answered May 3, 2018 at 9:59
12
  • It's giving an error at line HashSet Commented May 3, 2018 at 10:21
  • Which error are you getting? Commented May 3, 2018 at 10:34
  • HashSet cannot be resolved to a type Commented May 3, 2018 at 10:36
  • Import it from java.util package Commented 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> Commented May 3, 2018 at 10:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.