1

I am fetching all the links in the page and navigating to all links. In that one of the link is Logout. How do i skip/ignore Logout link from the loop?

I want to skip Logout link and proceed

List demovar=driver.findElements(By.tagName("a")); System.out.println(demovar.size());

   ArrayList<String> hrefs = new ArrayList<String>(); //List for storing all href values for 'a' tag

      for (WebElement var : demovar) {
          System.out.println(var.getText()); // used to get text present between the anchor tags
          System.out.println(var.getAttribute("href"));
          hrefs.add(var.getAttribute("href")); 
          System.out.println("*************************************");
      }

      int logoutlinkIndex = 0;

      for (WebElement linkElement : demovar) {
               if (linkElement.getText().equals("Log Out")) {
                           logoutlinkIndex = demovar.indexOf(linkElement);
                           break;
                }

      }

      demovar.remove(logoutlinkIndex);

      //Navigating to each link
      int i=0;
      for (String href : hrefs) {
          driver.navigate().to(href);
          System.out.println((++i)+": navigated to URL with href: "+href);
          Thread.sleep(5000); // To check if the navigation is happening properly.
          System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
sandy
  • 29
  • 6
  • Are you sure the link element text is "Log Out"? Also, consider using `for(int i = 0; i < ; i++) { ...` for your second and third loops, I think that's more of what you're looking for since you're referencing the index in both. – schil227 Jul 31 '19 at 15:14

2 Answers2

1

If you want to leave out the Logout link from the loop instead of creating the List as driver.findElements(By.tagName("a")); as an alternative you can use:

driver.findElements(By.xpath("//a[not(contains(.,'Log Out'))]"));

Reference

You can find a couple of relevant discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1
  1. Java approach to remove "not interesting" link using Stream.filter() function:

    List<String> hrefs = driver.findElements(By.className("a"))
            .stream()
            .filter(link -> link.getText().equals("Log out"))
            .map(link -> link.getAttribute("href"))
            .collect(Collectors.toList());
    
  2. Using XPath != operator solution to collect only links which text is not equal to Log Out:

    List<String> hrefs = driver.findElements(By.xpath("//a[text() != 'Log out']"))
            .stream()
            .map(link -> link.getAttribute("href"))
            .collect(Collectors.toList());
    
Dmitri T
  • 159,985
  • 5
  • 83
  • 133