admin管理员组

文章数量:1305935

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.

What am I doing wrong?

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.

What am I doing wrong?

Share Improve this question edited Sep 2, 2018 at 22:59 Grant Miller 29.1k16 gold badges155 silver badges168 bronze badges asked Sep 2, 2018 at 21:36 MaryMary 1,1454 gold badges22 silver badges44 bronze badges 1
  • Can you just print element? – Rashomon Commented Sep 2, 2018 at 21:38
Add a ment  | 

4 Answers 4

Reset to default 7

page.evaluate():

You can use page.evaluate() to get the innerHTML of an element:

const inner_html = await page.evaluate(() => document.querySelector('#myElement').innerHTML);

console.log(inner_html);

elementHandle.getProperty() / .jsonValue():

Alternatively, if you must use page.$(), you can access the innerHTML using a bination of elementHandle.getProperty() and elementHandle.jsonValue():

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.

Snippet sing page.$eval

const myContent = await page.$eval('#myDiv', (e) => e.innerHTML);
console.log(myContent);

Works great with jest-puppeter.

You have to use an asynchronous function evaluate.

In my case, I was using puppeteer/jest and all await* solutions was trowing

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

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);

本文标签: javascriptIn Puppeteerhow do I get the innerHTML of a selectorStack Overflow