在获取所有链接时,忽略循环中的注销链接并继续在 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
列出 demovar=driver.findElements(By.tagName("a"));System.out.println(demovar.size());
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("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
推荐答案
如果您想从循环中省略 Logout 链接,而不是将 List 创建为 driver.findElements(By.tagName("a"));
作为替代方案,您可以使用:
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:
- 量角器条件选择器
- 如何定位按钮通过 Python 使用 Selenium 的元素
- 什么确实 contains(., 'some text') 是指在 Selenium 中使用的 xpath 内
- xpath中的dot(.)如何在识别元素和匹配文本时采取多种形式
相关文章