Puppeteer - Getting Element Text
We can get element text in Puppeteer. This is done with the help of the textContent property. This property of the element is passed as a parameter to the getProperty method.
Syntax
The syntax of getting element text is as follows −
const n = await page.$("#txt")
const t = await (await n.getProperty('textContent')).jsonValue()
In the below image, let us obtain the text - About Tutorialspoint for the highlighted element −
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −
Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).
The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.
Right-click on the folder where the node_modules folder is created, then click on the New file button.
Step 2 − Enter a filename, say testcase1.js.
Step 3 − Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function getText(){
//launch browser in headless mode
const browser = await pt.launch()
//browser new page
const page = await browser.newPage()
//launch URL
await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
//identify element
const f = await page.$("[class='heading']")
//obtain text
const text = await (await f.getProperty('textContent')).jsonValue()
console.log("Text is: " + text)
}
getText()
Step 4 − Execute the code with the command given below −
node <filename>
So in our example, we shall run the following command −
node testcase1.js
After the command has been successfully executed, the text of the element - About Tutorialspoint gets printed in the console.