如何使用Selenium WebDriver检查404的URL?

stp*_*tpe 16 selenium webdriver

使用Selenium WebDriver检查URL GET是否成功返回(HTTP 200)最方便的方法是什么?

在这种特殊情况下,我最感兴趣的是验证当前页面的图像是否被破坏.

小智 10

试试这个:

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.
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我还需要使用Dave Hunt建议的naturalWidth检查,因此加载的表达式现在变为:boolean loaded =(Boolean)driver.executeScript("return arguments [0] .complete && typeof arguments [0] .naturalWidth!= \" undefined \"&& arguments [0] .naturalWidth> 0",image); (3认同)

Dav*_*unt 5

您可以使用getEval命令验证从页面上的每个图像的以下JavaScript返回的值.

@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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

添加了经过测试的TestNG/Java示例.