How to check URL for 404 using Selenium WebDriver?

前端 未结 6 1829
时光说笑
时光说笑 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: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"))
    

提交回复
热议问题