Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to modify an element in the DOM with Puppeteer before creating a screenshot?

I ran into an issue where I nave a fairly simple Node process that captures a screenshot. Is it possible to change the innerText of an HTML element using Puppeteer, just before the screen capture is acquired?

I have had success with using Puppeteer to type text in authentication fields and with logging into a site, but I was wondering if there is a similar method that would let me change the text in a specific element (using id or class name).

Example of the screen capture code I'm using:

const puppeteer = require('puppeteer');
 (async () => {
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    await page.goto('https://google.com')
    await page.screenshot({path: 'google.png'})
    await browser.close()
 })()

In this example, I would be interested in knowing if I can change the text content of an element such as the div with the ID 'lga' ... adding a text string for example.

Is that possible with Puppeteer?

Otherwise, it works great. I just need to insert some text into the page I'm performing a screenshot of. I'm using the command-line only on a Ubuntu 16.04 machine, and Node version 9, Puppeteer version 1.0.0.

like image 968
tamak Avatar asked Jan 30 '18 02:01

tamak


People also ask

How do you take a screenshot with a puppeteer?

Puppeteer Screenshot to Take Screenshot of an Element Simply copy the selector of an element by right-clicking on the element and selecting Inspect. Then, right-click the highlighted part and select Copy and Copy Selector.

How do you get page element puppeteer?

page. $eval() function is used to get the value for an element in puppeteer. $eval will stage two-parameter as an argument first parameter will be the selector and the second parameter will be element= element.


2 Answers

you can do that before screen

 await page.evaluate(() => {
    let dom = document.querySelector('#id');
    dom.innerHTML = "change to something"
 });
like image 177
Cr. Avatar answered Sep 28 '22 13:09

Cr.


page.$eval()

You can use page.$eval() to change the innerText of an element before taking a screenshot:

await page.$eval('#example', element => element.innerText = 'Hello, world!');

await page.screenshot({
  path: 'google.png',
});
like image 32
Grant Miller Avatar answered Sep 28 '22 14:09

Grant Miller