【问题标题】:Selenium: chrome driver makes screenshot just of visible part of pageSelenium:chrome 驱动程序只截取页面的可见部分
【发布时间】:2013-07-26 15:19:15
【问题描述】:

我需要使用 chrome 驱动程序对整页进行截图,但它只是部分截图。

File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

截图看起来是一个可见的矩形,下面有正确的信息和大的黑色区域。

【问题讨论】:

    标签: selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:

    这是一个已知的错误:https://code.google.com/p/chromedriver/issues/detail?id=294(仅适用于 Chrome 驱动程序,firefox 驱动程序可以正常工作)

    【讨论】:

    • 已经 3 年半了,还没有修复的迹象。 IE、Edge 和 Opera 也模仿了 chromes 的窃听行为,最后一次坚持是 firefox,直到 2016 年 11 月。现在最新的 firefox 驱动程序删除了整页屏幕截图以模仿这种行为。因此,在被标记为 chrome bug 3 年后,它现在已成为一项功能。
    • 另外,重要的是要注意W3C WebDriver Specification 要求屏幕截图仅适用于可见的视口。 Chrome 驱动程序的行为符合规范。
    【解决方案2】:

    可能值得尝试使用这个库:

    https://www.assertthat.com/posts/selenium_shutterbug_make_custom_screenshots_with_selenium_webdriver

    制作整页截图:

    Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS).save();
    

    (它使用滚动和缝合方法)

    github上的来源https://github.com/assertthat/selenium-shutterbug

    提供在 Chrome 中制作整页屏幕截图的能力和一些其他扩展功能,在 Windows 和 OS X 上进行了测试。

    在我当前的项目上成功使用。

    【讨论】:

    • 这是一款非常适合手头工作的实用工具。
    • 滚动和缝合很好,但粘贴标题会破坏它
    • 您可以在截屏前尝试将相对位置设置为置顶标题。类似于: ((JavascriptExecutor)webDriver).executeScript("arguments[0].style.position='relative'", stickyHeaderEl);
    【解决方案3】:

    你需要使用

    加载 html2canvas.js

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://github.com/niklasvh/html2canvas/releases/download/0.5.0-alpha1/html2canvas.js';
    document.head.appendChild(script);
    

    通过该命令下载整页截图的命令

    html2canvas(document.body).then(function(canvas) {
        var a = document.createElement('a');
            // toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
            a.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
            a.download = 'somefilename.jpg';
            a.click();
    })
    

    您可以使用 javascriptexecutor 调用此脚本并获得所需的结果,因为图像的下载会自动启动到您的默认下载位置,您可以使用 selenium 的 javascriptexecutor 命令的输入参数更改文件名。

    希望这会有所帮助!

    【讨论】:

    • 有希望的想法,但质量不是很好,很多网站都实施了跨域脚本预防措施:(
    【解决方案4】:

    我知道这是一个旧线程,但我想展示 Selenium 的 ITakesScreenshot 的用法。

    using OpenQA.Selenium;
    using System.Drawing.Imaging;
    
    ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(@"YourImageNameHere.png", ImageFormat.Png);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 2016-01-05
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多