Puppeteer: Get text content / inner HTML of an element
Problem:
You want to use puppeteer to automate testing a webpage. You need to get either the text or the inner HTML of some element, e.g. of
<div id="mydiv">
</div>
on the page.
Solution
// Get inner text
const innerText = await page.evaluate(() => document.querySelector('#mydiv').innerText);
// Get inner HTML
const innerHTML = await page.evaluate(() => document.querySelector('#mydiv').innerHTML);
Note that .innerText
includes the text of sub-elements. You can use the complete DOM API inside page.evaluate(...)
. You can use any CSS selector as an argument for document.querySelector(...)
.