Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an ElementHandle to a DOM element using puppeteer?

Tags:

puppeteer

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.

like image 827
Royi Namir Avatar asked Oct 30 '18 21:10

Royi Namir


People also ask

How do you get DOM element in puppeteer?

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.

What is ElementHandle in puppeteer?

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?

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.

What is an element handle?

Element Handle represents a remote element in the DOM of the browser. It implements useful methods for querying and interacting with DOM elements.


2 Answers

Use ElementHandle.evaluate():

const elementHandle: ElementHandle = await page.waitForSelector('.selector-list li')

elementHandle.evaluate(domElement => {
    domElement.tagName  
    // etc ...
})

like image 112
Mir-Ismaili Avatar answered Oct 06 '22 05:10

Mir-Ismaili


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.

like image 22
Thomas Dondorf Avatar answered Oct 06 '22 06:10

Thomas Dondorf