使用Selenium截屏元素? [英] Take a screenshot element with Selenium?

查看:131
本文介绍了使用Selenium截屏元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道要截取网页的屏幕截图1元素并将其转换为javascript中的base64吗?

Does anyone know take a screenshot 1 element of webpage and convert it to base64 in javascript?

推荐答案

这不是我的答案:从此处复制:

This is not my answer : Copied from here: How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

在Node.js中,我编写了下面的代码,该代码有效,但它不是基于硒的官方WebDriverJS,而是基于SauceLabs的WebDriver:WD.js和一个非常紧凑的图像库EasyImage.

In Node.js, I wrote the following code which works but it is not based on selenium's official WebDriverJS, but based on SauceLabs's WebDriver: WD.js and a very compact image library called EasyImage.

我只是想强调一下,您不能真正获取元素的屏幕截图,但是您应该做的是首先获取整个页面的屏幕截图,然后选择页面中喜欢的部分并裁剪该特定部分:

I just wanna emphasize that you cannot really take the screenshot of an element but what you should do is to first, take the screenshot of the whole page, then select the part of the page you like and crop that specific part:

browser.get(URL_TO_VISIT)
       .waitForElementById(dependentElementId, webdriver.asserters.isDisplayed, 3000)
       .elementById(elementID)
        .getSize().then(function(size) {
            browser.elementById(elementID)
                   .getLocation().then(function(location) {
                        browser.takeScreenshot().then(function(data) {
                            var base64Data = data.replace(/^data:image\/png;base64,/, "");
                            fs.writeFile(filePath, base64Data, 'base64', function(err) {
                                if (err) {
                                    console.log(err);
                                } 
                                else {
                                    cropInFile(size, location, filePath);
                                }
                                doneCallback();
                        });
                    });
                });
            }); 

cropInFileFunction如下:

And the cropInFileFunction, goes like this:

var cropInFile = function(size, location, srcFile) {
    easyimg.crop({
            src: srcFile,
            dst: srcFile,
            cropwidth: size.width,
            cropheight: size.height,
            x: location.x,
            y: location.y,
            gravity: 'North-West'
        },
        function(err, stdout, stderr) {
            if (err) throw err;
        });
};

这篇关于使用Selenium截屏元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆