我正在获取页面中的所有链接并导航到所有链接。其中一个链接是注销。我如何跳过/忽略循环中的注销链接?我想跳过注销链接并继续列表 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("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
2 回答
慕雪6442864
TA贡献1812条经验 获得超5个赞
如果您想从循环中省略注销链接而不是创建列表作为driver.findElements(By.tagName("a"));
替代方法,您可以使用:
driver.findElements(By.xpath("//a[not(contains(.,'Log Out'))]"));
www说
TA贡献1775条经验 获得超8个赞
使用Stream.filter()函数删除“不感兴趣”链接的 Java 方法:
List<String> hrefs = driver.findElements(By.className("a")) .stream() .filter(link -> link.getText().equals("Log out")) .map(link -> link.getAttribute("href")) .collect(Collectors.toList());
使用 XPath
!=
运算符解决方案仅收集文本不等于的链接Log Out
:List<String> hrefs = driver.findElements(By.xpath("//a[text() != 'Log out']")) .stream() .map(link -> link.getAttribute("href")) .collect(Collectors.toList());
添加回答
举报
0/150
提交
取消