How do I use Playwright to take screenshots of different webpages in Node.js?


Capture Screenshots with Playwright

First, let's install Playwright in your Node.js project. Run the following command in your project directory:

npm install playwright

Next, import the necessary functions from Playwright. If you're using Chromium browser, import it like this:

const { chromium } = require('playwright');

Now, launch a browser instance. This will create a new browser window for capturing screenshots.

const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();

Navigate to the webpage you want to capture a screenshot from using the page.goto() method.

await page.goto('https://ray.run');

To capture a screenshot and save it as a file, use the page.screenshot() method with appropriate options.

await page.screenshot({ path: 'screenshot.png' });

The screenshot will be saved as "screenshot.png" in your current working directory. Repeat these steps for different projects or screen sizes.

Finally, close the browser instance using browser.close() method to free up system resources.

await browser.close();

That's it! You've captured screenshots and saved them to files with Playwright. Remember to customize the code according to your specific requirements and project structure.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.