0

我正在尝试使用 Selenium for Java 在网页上查找所有损坏的链接。我用一个简单的教程尝试了它,它似乎可以在非常基本的网站上运行,但就我而言,DOM 似乎发生了变化,我经常得到一个StaleElementReferenceException.

我不太确定如何防止出现该异常或如何处理它。在这种异常的情况下,我基本上想跳过那个 URL 并继续我的循环。但是由于忽略异常是一种非常糟糕的做法,我想问你们如何更改我的代码以很好地处理异常。

public class BrokenLinkCollector {
    WebDriver driver;
    String webPage;
    public BrokenLinkCollector(WebDriver driver, String webPage) {
        this.driver = driver;
        this.webPage = webPage;
    }
    public void giveMeAllTheBrokenLinks(){
        String url = "";
        HttpURLConnection huc = null;
        int respCode = 200;

        driver.get(webPage);

        List<WebElement> links = driver.findElements(By.tagName("a"));

        Iterator<WebElement> it = links.iterator();

        while(it.hasNext()){

            WebElement we = it.next();
            url = we.getAttribute("href");

            if(url == null || url.isEmpty()){

                System.out.println("URL is either not configured for anchor tag or it is empty");
                continue;
            }

            try {
                huc = (HttpURLConnection)(new URL(url).openConnection());

                huc.setRequestMethod("HEAD");

                huc.connect();

                respCode = huc.getResponseCode();

                if(respCode >= 400){
                    System.out.println(url+" is broken");
                }
                else{
                    System.out.println(url+" works");
                }

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
} 
4

0 回答 0