当所有图像完全加载到网页中时,我正在尝试截取网页的屏幕截图。
虽然我认为解决方案已经在堆栈溢出上可用,但它们都不适合我。我找到的最接近的解决方案在这里:Wait for an image to be fully loaded Selenium WebDriver
但是,在这段代码中,用 javascript 执行器编写的 arg 不会返回 boolean 输出,这就是为什么它给我一个错误。
我正在使用以下代码,但在我的编译时错误中给出了“不兼容的操作数类型对象和 int"使用 equals 在这里也不适合我
waitexternal.until(new Function<WebDriver, Boolean>(){
@Override
public Boolean apply(WebDriver ldriver) {
ldriver = driver;
JavascriptExecutor js = (JavascriptExecutor) driver;
return js.executeScript("return jQuery.active") == 0;
//return (js.executeScript("return arguments[0]").equals("complete"));
}
}
);
最佳答案
您可以使用document.images
识别当前页面中的所有图像。您可以使用document.images.length
检查当前页面中有多少图像。
要检查这些图像是否正确加载,您可以在每个图像上应用 complete
属性,例如 document.images[0].complete
,它将返回 true如果图像已加载,否则为 false。
下面的代码将首先检查 DOM
是否已加载,如果 DOM 已加载,它将等待直到该页面中的所有图像加载完毕。
// Launching the browser
driver.get("http://www.google.com");
// Declaring and Casting driver to JavaScriptExecutor
JavascriptExecutor jse = (JavascriptExecutor) driver;
// Getting DOM status
Object result = jse.executeScript("return document.readyState;");
System.out.println("=> The status is : "+result.toString());
// Checking DOM loading is completed or not?
if(result.equals("complete")) {
// Fetching images count
result = jse.executeScript("return document.images.length");
int imagesCount = Integer.parseInt(result.toString());
boolean allLoaded = false;
// Checking and waiting until all the images are getting loaded
while(!allLoaded) {
int count = 0;
for(int i=0;i<imagesCount;i++) {
result = jse.executeScript("return document.images["+i+"].complete;");
boolean loaded = (Boolean) result;
if(loaded) count++;
}
// Breaking the while loop if all the images loading completes
if(count == imagesCount) {
System.out.println("=> All the Images are loaded...");
break;
} else {
System.out.println("=> Not yet loaded...");
}
Thread.sleep(1000);
}
}
但是使用上面的代码时要小心,因为如果元素根本没有加载,有时它可能会进入无穷大状态。
要检查特定元素是否已加载,您可以执行以下操作:
// To check a particular element is loaded or not?
WebElement googleLogo = driver.findElement(By.id("hplogo"));
boolean loaded = (Boolean) jse.executeScript("return arguments[0].complete;", googleLogo);
System.out.println("The google logo is loaded ? "+loaded);
要等待特定图像加载,您可以执行以下操作:
// To check a particular element is loaded or not?
WebElement googleLogo = driver.findElement(By.id("hplogo"));
while(!(Boolean) jse.executeScript("return arguments[0].complete;", googleLogo)) {
System.out.println("=> The google logo is not yet loaded...");
Thread.sleep(1000);
}
System.out.println("The google logo is loaded... ");
要了解有关 JavaScript 命令和 JavaScriptExecutor 的更多信息,请查看并订阅 this channel
来源:HTML DOM images Collection , Document.images
希望对你有帮助...
关于java - 如何在selenium java中等待,直到网页上的所有图像都正确加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734392/