How to check URL for 404 using Selenium WebDriver?

前端 未结 6 1777
时光说笑
时光说笑 2021-02-01 20:44

What is the most convenient way using Selenium WebDriver to check if an URL GET returns successfully (HTTP 200)?

In this particular case I\'m most interested in verifyin

6条回答
  •  鱼传尺愫
    2021-02-01 21:10

    You could use the getEval command to verify the value returned from the following JavaScript for each image on the page.

    @Test
    public void checkForBrokenImages() {
        selenium.open("http://www.example.com/");
        int imageCount = selenium.getXpathCount("//img").intValue();
        for (int i = 0; i < imageCount; i++) {
            String currentImage = "this.browserbot.getUserWindow().document.images[" + i + "]";
            assertEquals(selenium.getEval("(!" + currentImage + ".complete) ? false : !(typeof " + currentImage + ".naturalWidth != \"undefined\" && " + currentImage + ".naturalWidth == 0);"), "true", "Broken image: " + selenium.getEval(currentImage + ".src"));
        }
    }
    

    Updated:

    Added tested TestNG/Java example.

提交回复
热议问题