[英]In Puppeteer, how do I get the innerHTML of a selector?
At the moment, I'm trying the following:目前,我正在尝试以下操作:
const element = await page.$("#myElement");
const html = element.innerHTML;
I'm expecting the HTML to be printed, but instead I'm getting undefined
.我期待打印 HTML,但我得到了undefined
。
What am I doing wrong?我究竟做错了什么?
You can use page.evaluate()
to get the innerHTML
of an element:您可以使用page.evaluate()
来获取元素的innerHTML
:
const inner_html = await page.evaluate(() => document.querySelector('#myElement').innerHTML);
console.log(inner_html);
Alternatively, if you must use page.$()
, you can access the innerHTML
using a combination of elementHandle.getProperty()
and elementHandle.jsonValue()
:或者,如果您必须使用page.$()
,您可以使用elementHandle.getProperty()
和elementHandle.jsonValue()
的组合访问innerHTML
:
const inner_html = await (await (await page.$('#myElement')).getProperty('innerHTML')).jsonValue();
console.log(inner_html);
You can use page.$eval
to access innerHTML
pf specified DOM.您可以使用page.$eval
访问innerHTML
pf 指定的 DOM。
Snippet sing page.$eval Snippet sing page.$eval
const myContent = await page.$eval('#myDiv', (e) => e.innerHTML);
console.log(myContent);
Works great with jest-puppeter
.与jest-puppeter
一起使用效果jest-puppeter
。
You have to use an asynchronous function evaluate.您必须使用异步函数评估。
In my case, I was using puppeteer/jest and all await* solutions was trowing就我而言,我使用的是 puppeteer/jest 并且所有 await* 解决方案都在使用
error TS2531: Object is possibly 'null'
innerHTML with if statement was working for me(part of example) I was searching the member's table for the first unchecked element带有 if 语句的innerHTML对我有用(示例的一部分)我正在成员表中搜索第一个未选中的元素
while (n) {
let elementI = await page.$('div >' + ':nth-child(' + i + ')' + '> div > div div.v-input__slot > div');
let nameTextI = await page.evaluate(el => el.innerHTML , elementI);
console.log('Mistery' + nameTextI);
{...}
i++;
{...}
}
const html = await page.$eval("#myElement", e => e.innerHTML);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.