Example screenshot of not centered hackernews header:
I am trying to take a screenshot of a DOM element with Selenium (nodejs). I know this is not supported in Selenium, so my approach has been to take a fullscreen screenshot and then crop the image with the elements dimensions.
My issue is that the x and y location returned by element.getRect() are not lining up with the cropping of the image. I have also tried executing js (element.getClientBoundingRect()) in the browser.
I have tried using easyimage or sharp to crop the images but something about my dimensions are wrong. I have also tried resizing the image to the viewport width and height with no luck. Any help would be appreciated.
There are multiple similar questions on stack overflow, but no working approaches / solutions for a node environment.
const easyimg = require('easyimage')
const webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
const driver = new webdriver.Builder()
.forBrowser('firefox')
.build();
webdriver.WebDriver.prototype.saveScreenshot = async function (path, elem) {
const data = elem ? await elem.takeScreenshot() : await driver.takeScreenshot()
const base64Data = data.replace(/^data:image\/png;base64,/, "")
const error = fs.writeFileSync(`${path}.png`, base64Data, 'base64')
if (error) {
console.error(error)
}
}
(async () => {
await driver.get(url)
await driver.saveScreenshot('./images')
const cropInFile = async function (size, location, srcFile) {
await easyimg.crop({
src: srcFile,
dst: srcFile,
cropwidth: size.width,
cropheight: size.height,
x: location.x,
y: location.y,
gravity: 'NorthWest'
}
};
const { height, width, x, y } = await driver.executeScript(`return document.querySelector('${selector}').getBoundingClientRect()`)
const size = {height, width}
const location = {x, y}
await cropInFile(size, location, `./images/name.png`)
})()