简体   繁体   中英

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 .

What am I doing wrong?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM