Find broken images in page & image replace by another image

前端 未结 3 1974
说谎
说谎 2021-02-14 02:46

Hi I am using selenium webdriver 2.25.0 & faceing the some serious issues,

  1. how to find broken images in a page using Selenium Webdriver
  2. How to find th
相关标签:
3条回答
  • 2021-02-14 02:47

    The next lines are not optimized, but they could find broken images:

    List<WebElement> imagesList = _driver.findElements(By.tagName("img"));
    for (WebElement image : imagesList)
    {
        HttpResponse response = new DefaultHttpClient().execute(new HttpGet(image.getAttribute("src");));
        if (response.getStatusLine().getStatusCode() != 200)
            // Do whatever you want with broken images
    }
    

    Regarding your second issue, I think I didn't understand it correctly. Could you explain it with more detail?

    0 讨论(0)
  • 2021-02-14 03:05

    Based on the other answers, the code that eventually worked for me in an angular / protractor / webdriverjs setting is:

    it('should find all images', function () {
        var allImgElts = element.all(by.tagName('img'));
    
        browser.executeAsyncScript(function (callback) {
            var imgs = document.getElementsByTagName('img'),
                loaded = 0;
            for (var i = 0; i < imgs.length; i++) {
                if (imgs[i].naturalWidth > 0) {
                    loaded = loaded + 1;
                };
            };
            callback(loaded);
         }).then(function (loadedImagesCount) {
            expect(loadedImagesCount).toBe(allImgElts.count());
        });
    });
    

    The webdriver code counts the number of img elements, and the function executed within the browser context counts the number of successfully loaded elements. These numbers should be the same.

    0 讨论(0)
  • 2021-02-14 03:07

    The accepted answer requires that you use a proxy with an extra call to each image to determine if the images are broken or not.

    Fortunately, there is another way you can do this using only javascript (I'm using Ruby, but you can use the same code in any executeScript method across the WebDriver bindings):

    images = @driver.find_elements(:tag_name => "img")
    broken_images = images.reject do |image|
      @driver.execute_script("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", image)
    end
    # broken_images now has an array of any images on the page with broken links
    # and we want to ensure that it doesn't have any items
    assert broken_images.empty?
    

    To your other question, I would recommend just taking a screenshot of the page and having a human manually verify the resulting screenshot has the correct images. Computers can do the automation work, but humans do have to check and verify its results from time to time :)

    0 讨论(0)
提交回复
热议问题