java - 如何使用 getAttribute Selenium 防止获取重复的 href
问题描述
我不断从我正在测试的网站获得相同的链接。
这是我的代码 “
List<WebElement> activeLinks = new ArrayList<WebElement>();
//2.Iterate LinksList: Exclude all the links/images - doesn't have any href attribute and exclude images starting with javascript.
boolean breakIt = true;
for(WebElement link:AllTheLinkList)
{
breakIt = true;
try
{
//System.out.println((link.getAttribute("href")));
if(link.getAttribute("href") != null && !link.getAttribute("href").contains("javascript") && link.getAttribute("href").contains("pharmacy")) //&& !link.getAttribute("href").contains("pharmacy/main#"))
{
activeLinks.add(link);
}
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
breakIt = false;
}
if (breakIt)
{
continue;
}
}
//Get total amount of Other links
log.info("Other Links ---> " + (AllTheLinkList.size()-activeLinks.size()));
//Get total amount of links in the page
log.info("Size of active links and images in pharmacy ---> "+ activeLinks.size());
for(int j=0; j<activeLinks.size(); j++) {
HttpURLConnection connection = (HttpURLConnection) new URL(activeLinks.get(j).getAttribute("href")).openConnection();
connection.setConnectTimeout(4000);
connection.connect();
String response = connection.getResponseMessage(); //Ok
int code = connection.getResponseCode();
connection.disconnect();
//System.out.println((j+1) +"/" + activeLinks.size() + " " + activeLinks.get(j).getAttribute("href") + "---> status:" + response + " ----> code:" + code);
log.info((j+1) +"/" + activeLinks.size() + " " + activeLinks.get(j).getAttribute("href") + "---> status:" + response + " ----> code:" + code);
}
这是我的输出: 我一次又一次地获得相同的链接。就像他们在重复一样。
任何人都可以帮助我吗?
解决方案
尝试将列表项复制到集合,因为集合不允许重复。例如:
WebDriver driver = new ChromeDriver();
List<WebElement> anchors = driver.findElements(By.tagName("a"));
Set<WebElement> hrefs = new HashSet<WebElement>(anchors);
Iterator<WebElement> i = hrefs.iterator();
while(i.hasNext()) {
WebElement anchor = i.next();
if(anchor.getAttribute("href").contains(href)) {
anchor.click();
break;
}
}
希望这可以帮助。
推荐阅读
- javascript - 滚动到一组div时获取它的索引
- php - Laravel - 根据选择禁用日期选择器中的日期
- c# - Angular 6 中的强类型 SignalR Hub
- firebase - 您可以通过链接(即动态链接)共享 Firestore 文档吗?
- java - 尝试从 SwingWorker 更新时,Swing UI 冻结
- java - 使用 mockito 进行测试失败,但应用程序有效
- r - 在 RStudio 错误中分配值而不是过滤
- c# - 如何在不移动盒子的情况下进行 BoxCast()?
- firebase - 根据密钥获取 Firebase 条目
- python - 乘方函数