English 中文(简体)
Puppeteer - Getting Element Text
  • 时间:2024-11-05

Puppeteer - Getting Element Text


Previous Page Next Page  

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 highpghted element −

About Tutorialspoint for Highpghted 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-cpck on the folder where the node_modules folder is created, then cpck on the New file button.

Node Modules

Step 2 − Enter a filename, say testcase1.js.

Testcase1.JS

Step 3 − Add the below code within the testcase1.js file created.


//Puppeteer pbrary
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
Console

After the command has been successfully executed, the text of the element - About Tutorialspoint gets printed in the console.

Advertisements