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
-
use the bobble sorting methodVel Guru– Vel Guru2018年05月03日 09:34:31 +00:00Commented May 3, 2018 at 9:34
-
wanted to avoid repeated URL .Sayali Joglekar– Sayali Joglekar2018年05月03日 09:40:31 +00:00Commented May 3, 2018 at 9:40
-
What's your goal here? Are you trying to validate that there's no broken links?Florent B.– Florent B.2018年05月03日 14:26:59 +00:00Commented May 3, 2018 at 14:26
-
Trying to fetch Distinct URLSayali Joglekar– Sayali Joglekar2018年05月04日 06:27:58 +00:00Commented May 4, 2018 at 6:27
1 Answer 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
-
It's giving an error at line HashSetSayali Joglekar– Sayali Joglekar2018年05月03日 10:21:28 +00:00Commented May 3, 2018 at 10:21
-
Which error are you getting?Alexey R.– Alexey R.2018年05月03日 10:34:56 +00:00Commented May 3, 2018 at 10:34
-
HashSet cannot be resolved to a typeSayali Joglekar– Sayali Joglekar2018年05月03日 10:36:07 +00:00Commented May 3, 2018 at 10:36
-
Import it from java.util packageAlexey R.– Alexey R.2018年05月03日 10:40:20 +00:00Commented 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>Sayali Joglekar– Sayali Joglekar2018年05月03日 10:48:26 +00:00Commented May 3, 2018 at 10:48
Explore related questions
See similar questions with these tags.
default