Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

list - While fetching all links,Ignore logout link from the loop and continue navigation in selenium java

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("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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());
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...