首页 > 解决方案 > 如何使用 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);  
        }           

这是我的输出: 我一次又一次地获得相同的链接。就像他们在重复一样。

任何人都可以帮助我吗?

标签: javaselenium

解决方案


尝试将列表项复制到集合,因为集合不允许重复。例如:

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;
        }
    }

希望这可以帮助。


推荐阅读