This is how I currently get each DOM
property from an ElementHandle
:
let section: ElementHandle = await page.waitForSelector(".selector-list li");
let tagName = await section.$eval('a', (e) => e.tagName);
But here it's tagName
. What if I'd like want to inspect further properties ?
I don't want to write $eval
for each property.
Question:
How can I convert ElementHandle
to a Dom object , so I'd be able
to browse all properties ?
I want to get A
as a Dom object.
Puppeteer allows us to automate a web browser, and this also includes being able to use Javascript to get DOM elements on the page. In the web browsers we use, we would go to the developer tools and use the console to write Javascript code that can get elements.
ElementHandle prevents the DOM element from being garbage-collected unless the handle is disposed. ElementHandles are auto-disposed when their origin frame gets navigated. ElementHandle instances can be used as arguments in Page. $eval() and Page. evaluate() methods.
How do you find the value of an element in a puppeteer? page. $eval() function is used to get the value for an element in puppeteer. $eval will stage two-parameter as an argument first parameter will be the selector and the second parameter will be element= element.
Element Handle represents a remote element in the DOM of the browser. It implements useful methods for querying and interacting with DOM elements.
Use ElementHandle.evaluate()
:
const elementHandle: ElementHandle = await page.waitForSelector('.selector-list li')
elementHandle.evaluate(domElement => {
domElement.tagName
// etc ...
})
The better way would be to execute the code on the page via page.evaluate and return the results. That way you can return an array with values:
const result = await page.evaluate(() => {
const elements = document.querySelectorAll(".selector-list li");
// do something with elements, like mapping elements to an attribute:
return Array.from(elements).map(element => element.tagName);
});
result
will then be an array with the attribute values of tagName
of each element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With