javascript - Selenium 关于 loadTimeout 的屏幕截图

标签 javascript java firefox selenium selenium-webdriver

我在我的框架中使用selenium webdriver(2.45.0版,在我的ubuntu 14.04中带有FFv38.0.5),它访问一些url来检查其可用性并返回屏幕截图和一些数据。如果页面向上或向下,我可以获得所有数据和屏幕截图,这一切都很好,但问题是当页面超时时,selenium 无法捕获屏幕截图并引发异常。我尽力找到某种方法从超时页面获取屏幕截图,但失败了,这就是为什么我将其发布在这里作为最后的手段。我的代码如下,

driver = new FirefoxDriver(fbp, profile, desiredCapabilities);
driver.manage().timeouts().pageLoadTimeout(loadTimeout , TimeUnit.SECONDS);
try {
    driver.get(url);
} catch (Exception e) {
   File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);           
   FileUtils.copyFile(scrFile, new File("path-to-png"));
}

我得到的异常(exception)是

Could not take screenshot of current page - Error: Page is not loaded yet, try later
Command duration or timeout: 7 milliseconds
Build info: version: '2.46.0', revision: '87c69e2', time: '2015-06-04 16:17:10'
System info: host: 'santhosh-2840', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '3.13.0-37-generic', java.version: '1.7.0_65'
Session ID: a0754b4f-ff3a-4ee1-8ace-6886eaa958b1
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=LINUX, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, nativeEvents=false, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=38.0.5}]

是否有办法从 selenium 获取 timeodut 页面的屏幕截图?

p.s:我确实知道超时页面不会有任何 dom 内容,s​​elenium 将在其上获取内容长度来计算其屏幕截图大小,不知何故我还需要获取超时页面的屏幕截图。

TIA

最佳答案

运行代码且页面超时时出现的错误是什么?

我认为你必须专门捕获TimeoutException:

private void takeScreenshot() {
    try {
        File source = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        path = "./path/to/screenshots/screenshot.png";

        source.setWritable(true);

        if(source.canWrite()) {
            FileUtils.copyFile(source, new File(path));
        }
     } catch(IOException e) {
         // ...
     } catch(Exception e) {
         // ...
     }
}

...

try {
    driver.get(url);
} catch (TimeoutException e) {
    takeScreenshot();
}

这对我有用。

关于javascript - Selenium 关于 loadTimeout 的屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33649978/

相关文章:

javascript - 方法如何将参数传递给处理程序?

javascript - PHP/jQuery 缩短字符串并在单击时显示更多内容

java - 在 Java 项目中更新 Twitter4j

javascript - 截取 "invisible"网页的屏幕截图

javascript - jQuery 悬停动画仅在不同类之间

javascript - 在 JavaScript 中,如果 "delete"一个不存在的属性会发生什么?

java - java while 循环中的 VariableDeclaratorID 异常

java - 即使文件中有文本,BufferedReader 也会返回 null

css - Firefox 上的 Flex loadStyleDeclarations 错误 2035

c# - 如何使用 C# 应用程序向 Firefox 扩展发送消息?