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

匆匆过客 提交于 2020-01-24 20:29:56

问题


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("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

回答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:

  • How to locate the button element using Selenium through Python
  • What does contains(., 'some text') refers to within xpath used in Selenium
  • How does dot(.) in xpath to take multiple form in identifying an element and matching a text



回答2:


  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());
    


来源:https://stackoverflow.com/questions/57293901/while-fetching-all-links-ignore-logout-link-from-the-loop-and-continue-navigatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!