Playwright is a powerful and versatile automation library developed by Microsoft. It enables developers and testers to automate web applications across multiple browsers easily.
Playwright automation supports Chromium, Firefox, and WebKit, allowing you to test across different browsers. It supports programming languages such as Java, Python, C#, and NodeJS. Playwright comes with an Apache 2.0 license and is most popular in NodeJS and Javascript/Typescript.
Browserless is a cloud-based browser solution designed for efficient automation, web scraping, and testing. Utilizing Nstbrowser's fingerprint library, Browserless provides random fingerprint switching for smooth data collection and automation processes.
Its robust cloud infrastructure allows for easy management of multiple browser instances, simplifying the handling of automation tasks.
Do you have any wonderful ideas or doubts about web scraping and Browserless?
Let's see what other developers are sharing on Discord and Telegram!
The advantages of Playwright automation include:
The Playwright architecture is designed specifically for browser automation, providing a powerful, flexible, and high-performance framework. It supports multiple browser engines, independent browser environments, and powerful APIs, and is suitable for browser automation tasks such as web crawling and automated testing. Its architecture ensures the reliability, efficiency, and easy maintenance of tests and scripts.
1. Client (Automation Script):
Playwright natively supports JavaScript and TypeScript, and also provides bindings for Java, Python, and C#, allowing users to write automation scripts in these languages.
Users write test scripts in their preferred language, including test cases, interactive commands, and assertions. JSON is often used for configuration and data exchange to ensure efficient data transmission.
2. WebSocket connection:
3. Server-side (Node.js):
4. Browser Automation (CDP and CDP+):
Before we start, we need to have a Browserless service. Using Browserless can solve complex web crawling and large-scale automation tasks, and it has now achieved fully managed cloud deployment.
Browserless adopts a browser-centric approach, provides powerful headless deployment capabilities, and provides higher performance and reliability. For more information about Browserless, you can click here to learn more.
Before we start, let's determine the goal of this test. We will use Playwright
to perform form validation and obtain the error information provided by the website. From the normal page access interaction, we will experience:
Follow the steps below to install Playwright and run the test script
Step 1: Create a new folder in Vs code
Step 2: Open the Vs code terminal and run the following command
npm init -y
npm install playwright @playwright/test
Step3: Create related files
playwright.config.ts
fileimport { defineConfig } from '@playwright/test';
export default defineConfig({
// test files to run
testDir: './tests',
// timeout for each test
timeout: 30 * 1000,
// timeout for the entire test run
expect: {
timeout: 30 * 1000,
},
// Reporter to use
reporter: 'html',
// Glob patterns or regular expressions to ignore test files.
testIgnore: '*test-assets',
// Glob patterns or regular expressions that match test files.
testMatch: '*tests/*.spec.ts',
});
tests/browserless.spec.ts
test scripts
- Launching the browser requires passing in the relevant configuration (for complete configuration, see LaunchNewBrowser)
- The
proxy
parameter is required
import { chromium } from 'playwright';
import { test, expect, Page } from '@playwright/test';
let page: Page;
async function createBrowser() {
const token = 'your api token'; // required
const config = {
proxy:
'your proxy', // required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080
// platform: 'windows', // support: windows, mac, linux
// kernel: 'chromium', // only support: chromium
// kernelMilestone: '124', // support: 113, 120, 124
// args: {
// '--proxy-bypass-list': 'detect.nstbrowser.io',
// }, // browser args
// fingerprint: {
// userAgent:
// 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36',
// },
};
const query = new URLSearchParams({
token: token, // required
config: JSON.stringify(config),
});
const browserWSEndpoint = `ws://less.nstbrowser.io/connect?${query.toString()}`;
const browser = await chromium.connectOverCDP(browserWSEndpoint);
const context = await browser.newContext();
const page = await context.newPage();
return page;
}
function logger(text: string) {
console.log(text);
}
test.beforeEach(async () => {
if (!page) {
page = await createBrowser();
}
await page.goto('https://www.airbnb.com/');
});
test.describe('Browserless Test', () => {
test('Verify Airbnb Website Login Error Message', async () => {
try {
logger(`go to the target page ${await page.url()}`);
// judge the title of the page
const title = await page.title();
logger(`page title: ${title}`);
// wait for select the button aria-label="Main navigation menu"
await page.waitForSelector('[aria-label="Main navigation menu"]');
// click the button aria-label="Main navigation menu"
await page.click('[aria-label="Main navigation menu"]');
// wait for the a text is Sign up
await page.waitForSelector('a:has-text("Sign up")');
// click the a text is Sign up
await page.click('a:has-text("Sign up")');
await page.click('span:has-text("Continue")');
// // get the error message by id="phone-number-error-phone-login"
const text = await page.textContent('#phone-number-error-phone-login');
logger(`error message: ${text}`);
expect(text).toBe('Phone number is required.');
await page.close();
await page.context().close();
} catch (error) {
console.error(error);
}
});
});
The project file structure is as follows
After the above project initialization, we can start running our project! Now open the Vs code terminal and run:
npx playwright test
The commands here can be mainly broken down into
npx
command to execute the playwright commandAfter executing the above command, we will see the following output results. Here, each important result of the test execution process is output, and we can see that our test case has passed.
We can view our test report by running the following command:
npx playwright show-report
The report shows in detail each step of the execution command, execution status, and final output results.
Playwright provides a powerful and versatile test automation framework, making it a valuable tool for developers and testers. Its ability to handle multiple browsers, provide cross-platform support, and provide rich interaction and verification APIs make it stand out in the field of test automation.
Through the comprehensive step-by-step tutorial in this blog, we learned:
Combined with Browserless, users can leverage the power of Playwright to create reliable, efficient, and scalable automated tests, simplifying the testing process, reducing manual workload, and ensuring a more powerful and seamless user experience.
Start experiencing the power of Browserless now!