Skip to main content

Page methods

Understand that the Page object has many different methods to offer, and learn how to use two of them to capture a page's title and take a screenshot.

Other than having methods for interacting with a page and waiting for events and elements, the Page object also supports various methods for doing other things, such as reloading, screenshotting, changing headers, and extracting the page's content.

Last lesson, we left off at a point where we were waiting for the page to navigate so that we can extract the page's title and take a screenshot of it. In this lesson, we'll be learning about the two methods we can use to easily achieve both of those things.

Grabbing the title

Two main page functions exist that will return general data:

  1. page.content() will return the entire HTML content of the page.
  2. page.title() will return the title of the current page found in the <title> tag.

For our case, we'll utilize the page.title() function to grab the title and log it to the console:

// Grab the title and set it to a variable
const title = await page.title();

// Log the title to the console


The page.screenshot() function will return a buffer which can be written to the filesystem as an image:

// Take the screenshot and write it to the filesystem
await page.screenshot({ path: 'screenshot.png' });

The image will by default be .png. To change the image to .jpeg type, set the (optional) type option to jpeg.

Final code

Here's our final code which extracts the page's title, takes a screenshot and saves it to our project's folder as screenshot.png:

import { chromium } from 'playwright';

const browser = await chromium.launch({ headless: false });

// Create a page and visit Google
const page = await browser.newPage();
await page.goto('');

// Agree to the cookies policy
await'button:has-text("I agree")');

// Type the query and visit the results page
await page.type('input[title="Search"]', 'hello world');

// Click on the first result
await'.g a');
await page.waitForLoadState('load');

// Grab the page's title and log it to the console
const title = await page.title();

// Take a screenshot and write it to the filesystem
await page.screenshot({ path: 'screenshot.png' });

await browser.close();

When you run this code, you should see this logged to the console:

"Hello, World!" program - Wikipedia

Additionally, you should see a new image named screenshot.png in your project's folder that looks something like this:

Screenshot from Playwright/Puppeteer

Next up

In the next exciting lesson, we'll gain a solid understanding of the two different contexts we can run our code in when using Puppeteer and Playwright, as well as how to run code in the context of the browser.