在获取所有链接时,请忽略循环中的注销链接并继续在Selenium Java中导航 [英] 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
列表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("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
推荐答案
如果要从循环中删除登出链接,而不是将 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:
- 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
这篇关于在获取所有链接时,请忽略循环中的注销链接并继续在Selenium Java中导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!