有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

这是我的输出: I'm getting same links again and again. it's like they are repeating.

有人能帮我吗


共 (1) 个答案

  1. # 1 楼答案

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

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

    希望这有帮助