有谁知道截取网页的截图1元素并在javascript中将其转换为base64?
答案 0 :(得分:2)
这不是我的答案:从这里复制:How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?
在Node.js中,我编写了以下代码,但它不是基于selenium的官方WebDriverJS,而是基于SauceLabs的WebDriver:WD.js和一个非常紧凑的图像库,名为EasyImage
我只想强调你不能真正拍摄元素的截图,但你应该做的是首先,截取整个页面的截图,然后选择你喜欢的页面部分并裁剪该特定部分:< / p>
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就像这样:
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;
});
};
答案 1 :(得分:0)
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().usingServer('http://localURL:4444/wd/hub').withCapabilities({'browserName': 'chrome'}).build();
//driver.get([URL to webserver on my local machine])
driver.findElement(webdriver.By.xpath('//img[@id="tree_image0358"]'));
driver.takeScreenshot("c:\\selenium_local_map\\out1.png");
driver.takeScreenshot().then(
function(image, err) {
require('fs').writeFile('out.png', image, 'base64', function(err {
console.log(err);
});
}
);