How to check URL for 404 using Selenium WebDriver?

前端 未结 6 1758
时光说笑
时光说笑 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.

    0 讨论(0)
  • 2021-02-01 21:15

    I don't think that first response will work. When I src a misnamed image, it throws a 404 error as expected. However, when I check the javascript in firebug, that (broken) image has .complete set to true. So, it was a completed 404, but still a broken image.

    The second response seems to be more accurate in that it checks that it's complete and then checks that there is some width to the image.

    I made a python version of the second response that works for me. Could be cleaned up a bit, but hopefully it will help.

    def checkForBrokenImages(self):
        sel = self.selenium
        imgCount = int(sel.get_xpath_count("//img"))
        for i in range(0,imgCount):
            isComplete = sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].complete")
            self.assertTrue(isComplete, "Bad Img (!complete): "+sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].src"))
            typeOf = sel.get_eval("typeof selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].naturalWidth")
            self.assertTrue(typeOf != 'undefined', "Bad Img (w=undef): "+sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].src"))
            natWidth = int(sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].naturalWidth"))
            self.assertTrue(natWidth > 0, "Bad Img (w=0): "+sel.get_eval("selenium.browserbot.getCurrentWindow().document.images[" + str(i) + "].src"))
    
    0 讨论(0)
  • 2021-02-01 21:18

    Instead of traversing in Java, it may be faster to call javascript only once for all images.

    boolean allImgLoaded = (Boolean)((JavascriptExecutor) driver).executeScript(
        "return Array.prototype.slice.call(document.images).every(" 
        + "function (img) {return img.complete && img.naturalWidth > 0;});");
    
    0 讨论(0)
  • 2021-02-01 21:18

    One of the alternative solutions is analyzing web server logs after test executing. This approach allows to catch not only missed images, but css, scripts and other resources.

    Description of how to do it is here.

    0 讨论(0)
  • 2021-02-01 21:20

    Funda for Checking 404:

    Basically 404s can be checked via HTTP Response of the URL.

    Step 1: Import the Library for HTTPTestAPI
    Step 2: Create the HTTPRequest.

    String URL="www.abc.com";
    HTTPRequest request = new HTTPRequest(URL);
    
    //Get the response code of the URL
    int response_code = request.getResponseCode();
    
    //Check for 404:
    if(response_code == 404)
        FAIL -- THE URL is leading to 404.
    else
        PASS
    
    0 讨论(0)
  • 2021-02-01 21:21

    Try this:

    List<WebElement> allImages = driver.findElements(By.tagName("img"));
    for (WebElement image : allImages) {
      boolean loaded = ((JavaScriptExecutor) driver).executeScript(
          "return arguments[0].complete", image);
      if (!loaded) {
        // Your error handling here.
      }
    }
    
    0 讨论(0)
提交回复
热议问题