javascript 是否可以在创建屏幕截图之前使用 Puppeteer 修改 DOM 中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48513066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to modify an element in the DOM with Puppeteer before creating a screenshot?
提问by tamak
I ran into an issue where I nave a fairly simple Node process that captures a screenshot. Is it possible to change the innerTextof an HTML element using Puppeteer, just before the screen capture is acquired?
我遇到了一个问题,我没有一个相当简单的 Node 进程来捕获屏幕截图。是否可以在innerText获取屏幕截图之前使用 Puppeteer更改HTML 元素的 ?
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).
我已经成功地使用 Puppeteer 在身份验证字段中键入文本并登录到站点,但我想知道是否有类似的方法可以让我更改特定元素中的文本(使用 id 或类名)。
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.
在这个例子中,我很想知道我是否可以更改元素的文本内容,例如 ID 为“lga”的 div……例如添加一个文本字符串。
Is that possible with Puppeteer?
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.
否则,效果很好。我只需要在我正在执行屏幕截图的页面中插入一些文本。我仅在 Ubuntu 16.04 机器和 Node 版本 9、Puppeteer 版本 1.0.0 上使用命令行。
回答by Cr.
you can do that before screen
你可以在屏幕前这样做
await page.evaluate(() => {
let dom = document.querySelector('#id');
dom.innerHTML = "change to something"
});
回答by Grant Miller
page.$eval()
page.$eval()
You can use page.$eval()to change the innerTextof an element before taking a screenshot:
您可以在截屏之前使用page.$eval()更改innerText元素的 :
await page.$eval('#example', element => element.innerText = 'Hello, world!');
await page.screenshot({
path: 'google.png',
});

