I'm trying to get all button elements from a webpage using the code:
const test = await page.evaluate(() => {
return document.querySelectorAll("button")
})
console.log(test)
When I log the test variable it yields 'undefined', while when I run the following code on chrome's console:
document.querySelectorAll("button")
It yields the correct amount of elements.
You need to do everything that works with the HTMLElements in the context of the website (so from within the evaluate callback).
At the end of evaluate you leave the context of the site you are very limited to what you can return from evaluate.
The data you return from evaluate has to be Serializable, DOM Elements are not Serializable in a meaningful way.
So you can only return something that is serializable using JSON.stringify.
My end goal is to check all buttons until I find a button with certain innerText and then click it.
Then you probably don't want to use evaluate, query for the elements from outside of the sites context using $ or $$
let buttons = await page.$$("button")
To get the text from the ElementHandler you can use:
const text = await page.evaluate(element => element.textContent, buttons[0]);
or
const text = await (await buttons[0].getProperty('textContent')).jsonValue();
A click can be performed with:
await buttons[0].click()
The values returned from evaluate must be serializable by JSON since puppeteer is returning chrome API calls, try this:
const test = await page.evaluate() => {
let elements = Array.from(document.querySelectorAll("button"));
let buttons = elements.map(element => {
return element
})
return buttons;
}