Scraping and verification

Evaluating JavaScript

Execute JavaScript function in the page:

  1. const href = await page.evaluate(() => document.location.href);

If the result is a Promise or if the function is asynchronous evaluate will automatically wait until it’s resolved:

  1. const status = await page.evaluate(async () => {
  2. const response = await fetch(location.href);
  3. return response.status;
  4. });

Get object handle and use it in multiple evaluations:

  1. // Create a new array in the page, write a reference to it in
  2. // window.myArray and get a handle to it.
  3. const myArrayHandle = await page.evaluateHandle(() => {
  4. window.myArray = [1];
  5. return myArray;
  6. });
  7. // Get current length of the array using the handle.
  8. const length = await page.evaluate(
  9. (arg) => arg.myArray.length,
  10. { myArray: myArrayHandle }
  11. );
  12. // Add one more element to the array using the handle
  13. await page.evaluate((arg) => arg.myArray.push(arg.newElement), {
  14. myArray: myArrayHandle,
  15. newElement: 2
  16. });
  17. // Get current length of the array using window.myArray reference.
  18. const newLength = await page.evaluate(() => window.myArray.length);
  19. // Release the object when it's no longer needed.
  20. await myArrayHandle.dispose();

API reference

Capturing screenshot

  1. // Save to file
  2. await page.screenshot({path: 'screenshot.png'});
  3. // Capture full page
  4. await page.screenshot({path: 'screenshot.png', fullPage: true});
  5. // Capture into buffer
  6. const buffer = await page.screenshot();
  7. console.log(buffer.toString('base64'));
  8. // Capture given element
  9. const elementHandle = await page.$('.header');
  10. await elementHandle.screenshot({ path: 'screenshot.png' });

API reference

Page events

You can listen for various events on the page object. Following are just some of the examples of the events you can assert and handle:

“console” - get all console messages from the page

  1. page.on('console', msg => {
  2. // Handle only errors.
  3. if (msg.type() !== 'error')
  4. return;
  5. console.log(`text: "${msg.text()}"`);
  6. });

“dialog” - handle alert, confirm, prompt

  1. page.on('dialog', dialog => {
  2. dialog.accept();
  3. });

“popup” - handle popup windows

  1. const [popup] = await Promise.all([
  2. page.waitForEvent('popup'),
  3. page.click('#open')
  4. ]);

API reference

Handling exceptions

Listen uncaught exceptions in the page:

  1. // Log all uncaught errors to the terminal
  2. page.on('pageerror', exception => {
  3. console.log(`Uncaught exception: "${exception}"`);
  4. });
  5. // Navigate to a page with an exception.
  6. await page.goto('data:text/html,<script>throw new Error("Test")</script>');

API reference