Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Playwright First Script

Playwright First Script

Before writing code, it is essential to understand Playwright's core concepts. The three most central objects are Browser, BrowserContext, and Page, which form the foundation of your interaction with web pages:

The relationship among the three:

A Browser can contain multiple BrowserContext, and one BrowserContext can contain multiple Page. Usually, we only need one Browser and one BrowserContext, but in scenarios that require data isolation,BrowserContext becomes very useful.


Writing Your First Script

Next we will write a simple script that launches a browser, visits Baidu, and takes a screenshot.

Create an environment named baidu_script.js file and paste the following code:

Example

const

{

chromium

}

=

require

(

'playwright'

)

;

(

async

(

)

=>

{

 

// Launch the browser and create a new browser context.

 

const

browser

=

await chromium.

launch

(

{

headless

:

false

}

)

;

// headless: false shows the browser window

 

const

context

=

await browser.

newContext

(

)

;

 

const

page

=

await context.

newPage

(

)

;

 

// Navigate to the website you want to visit.

  await page.

goto

(

'https://www.baidu.com'

)

;

 

// Enter text in the search box.

  await page.

fill

(

'#kw'

,

'Playwright'

)

;

 

// Press Enter or click the search button.

  await page.

press

(

'#kw'

,

'Enter'

)

;

 

// Wait for navigation to complete; this is important to ensure the page has fully loaded.

  await page.

waitForNavigation

(

)

;

 

// Take a screenshot and save it.

  await page.

screenshot

(

{

path

:

'baidu_search_results.png'

}

)

;

 

// Print the current page's title.

  console.

log

(

`The page title is

:

$

{

await page.

title

(

)

}

`

)

;

 

// Close the browser.

  await browser.

close

(

)

;

}

)

(

)

;

Code Explanation:

Running the Script

Open a terminal or command prompt, navigate to your project directory, and run the following command:

node baidu_script.js

After running it, you will see a browser window open automatically, load the Baidu homepage, and then close. In your project folder, a screenshot file named baidu_homepage.png will be generated.

Debug Mode

When writing more complex scripts, you may need to debug.

Playwright provides a powerful debugging tool. We just need to add PWDEBUG=1:

PWDEBUG=1 node baidu_script.js

before the command line when running the script. After running it, you will see a Playwright debug window where you can step through the code, inspect page elements, and see every step of the script in real time, which is very helpful for locating problems.

Viewing the Run Results

In addition to command-line output and screenshot files, you can also check the script's run results in the following ways: