'puppeteer page.evaluate returns an empty object [duplicate]

im trying to scrape a price element from a website using the page.evaluate method, but it allways returns {} when i console.log the result. here's the code:

const browser = await pptr.launch()
const page = await browser.newPage()
await page.goto("url")
const price = await page.evaluate(() => {
    return document.querySelector("selector")
})
console.log(price) // returns {}

I've tried using page.$(selector) too, it returns an array containing ElementHandle and bunch of other stuuf whitch i don't fully understand what they are

thanks!



Solution 1:[1]

You are trying to pass an element handle from the browser to your puppeteer application. To transfer data from the browser puppeteer uses JSON.stringify and the element handle gets transformed into an empty object.

You could try to pass something else back to your application like the text content of the element.

const browser = await pptr.launch()
const page = await browser.newPage()
await page.goto("url")
const price = await page.evaluate(() => {
    return document.querySelector("selector").textContent
})
console.log(price)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jkoch