Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer - how to use page.evaluateHandle

I have some trouble using the newest version of puppeteer.

I'm using puppeteer version 0.13.0.

I have a site with this element:

<div class="header">hey there</div>

I'm trying to run this code:

  const headerHandle = await page.evaluateHandle(() => {
    const element = document.getElementsByClassName('header');
    return element;
  });

Now the headerHandle is a JSHandle with a description: 'HTMLCollection(0)'.

If I try to run headerHandle.getProperties() and try to console.log I get Promise { <pending> }.

If I just try to get the element like this:

  const result = await page.evaluate(() => {
    const element = document.getElementsByClassName('header');
    return Promise.resolve(element);
  });

I get an empty object.

How do I get the actual element or the value of the element?

like image 391
Kristoffer Avatar asked Jan 08 '18 09:01

Kristoffer


1 Answers

Puppeteer has changed the way evaluate works, the safest way to retrieve DOM elements is by creating a JSHandle, and passing that handle to the evaluate function:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'networkidle2' });

  const jsHandle = await page.evaluateHandle(() => {
    const elements = document.getElementsByTagName('h1');
    return elements;
  });
  console.log(jsHandle); // JSHandle

  const result = await page.evaluate(els => els[0].innerHTML, jsHandle);
  console.log(result); // it will log the string 'Example Domain'

  await browser.close();
})();

For reference: evalute docs, issue #1590, issue #1003 and PR #1098

like image 120
Fabio Antunes Avatar answered Sep 18 '22 12:09

Fabio Antunes