有人能帮我解释一下使用SeleniumWebDriver进行图像验证的javascript代码吗?
我计划使用下面的代码来测试网页上的图像是否正确加载。有人能解释一下这个javascript代码是如何验证图像是否被加载的吗有人能帮我解释一下使用SeleniumWebDriver进行图像验证的javascript代码吗?,javascript,selenium,selenium-webdriver,webdriver,webpage,Javascript,Selenium,Selenium Webdriver,Webdriver,Webpage,我计划使用下面的代码来测试网页上的图像是否正确加载。有人能解释一下这个javascript代码是如何验证图像是否被加载的吗 ArrayList<WebElement> imgElements = driver.findElements(By.xpath("//*[contains(@src, '.gif')] | //*[contains(@src, '.png')]"); for (WebElement element : imgElements){ boolean ima
ArrayList<WebElement> imgElements = driver.findElements(By.xpath("//*[contains(@src, '.gif')] | //*[contains(@src, '.png')]");
for (WebElement element : imgElements){
boolean imageLoaded = (boolean) ((JavascriptExecutor) driver).executeScript("return arguments[0].complete && "+ "typeof arguments[0].naturalWidth != \"undefined\" && "+"arguments[0].naturalWidth > 0", element);
if (!imageLoaded)
{
System.out.println("Found broken image: "element.getAttribute("src"))
}
ArrayList imgElements=driver.findElements(By.xpath(“/*[contains(@src,.gif')]”)|/*[contains(@src,.png')]);
for(WebElement:imgElements){
boolean imageLoaded=(boolean)((JavascriptExecutor)driver).executeScript(“返回参数[0]。参数[0]的完整类型和“+”类型。naturalWidth!=\“未定义”和“+”参数[0]。naturalWidth>0”,元素);
如果(!imageLoaded)
{
System.out.println(“找到损坏的图像:”element.getAttribute(“src”))
}
}就我所见,
参数[0]
引用一个HTMLImageElement
。该对象有一个属性,指示图像是否加载。它还有naturalHeight
和naturalWidth
属性,这些属性共同指定加载后图像的固有大小。如果这些属性不可用,则返回0
使用我们刚刚学到的内容,我们可以很容易地看到以下代码将如何确定图像是否已加载:
return arguments[0].complete
&& typeof arguments[0].naturalWidth != 'undefined'
&& arguments[0].naturalWidth > 0;
然而,只有第二个条件涉及检查未定义的
,这似乎与MDN所说的不一致,因为自然宽度
不可用时应为0
,而不是未定义的