playwright basic tutorial

playwright

introduce

Playwright is an automated testing tool developed by Microsoft that can be used to test web applications. It supports multiple programming languages ​​and multiple browsers, including Chrome, Firefox, and WebKit. It provides a set of APIs that allow developers to simulate user actions in the browser, such as clicking, entering text and navigating to different pages, while capturing screenshots and videos.

Key features of Playwright include:

  1. Cross-Browser Support: Playwright supports multiple browsers, including Chrome, Firefox, and WebKit. This means developers can perform automated tests in different browsers without changing the test code.

  2. Multilingual support: Playwright supports multiple programming languages, including JavaScript, TypeScript, Python, and Java. This allows developers to write automated tests in their preferred language.

  3. Built-in waiting mechanism: Playwright has a built-in waiting mechanism that automatically waits for page loads, network requests, and element visibility. This allows developers to write more stable tests without having to manually add wait times.

  4. Screenshots and Video Recordings: Playwright can capture screenshots and video recordings. This is useful for debugging cases where tests fail and can help developers find problems faster.

  5. Fast execution: Playwright is built on the Chrome DevTools protocol, it can leverage the capabilities of the Chrome DevTools protocol,

Playwright can be used in a variety of browser automation scenarios, including testing, crawling, data mining, and automation tasks. It provides full control over the browser, including the browser's page and network layers, allowing developers to more finely control and simulate user actions and interactions. In the field of testing, Playwright is characterized by fast, reliable and scalable, supports multi-browser execution and parallel execution, which can greatly improve test efficiency.

In addition to basic browser operations, Playwright also provides some advanced usage, including:

  1. Video recording: You can record the browser's screen operations and save them in the form of video.
  2. Timeline tracking: Each network request and DOM event of the browser can be recorded and displayed in the form of a timeline.
  3. Global parallel execution: Multiple browser instances can be executed simultaneously to speed up test execution.
  4. Customized browser instance: The startup configuration of the browser instance can be customized to meet testing needs.

Basic usage

Enter text in the input box

You can use fill()the method to enter text into the input box. For example:

await page.fill('input[name="username"]', 'testuser')

This code will enter the text "testuser" into the input box named "username".

Click on page element

You can use click()methods to click elements on the page. For example:

await page.click('button[id="submit"]')

This code will click the button with the ID "submit" on the page.

Select an option from the drop-down list

You can use selectOption()methods to select options from drop-down lists. For example:

await page.selectOption('select[name="country"]', 'USA')

This code will select the "USA" option from the drop-down list named "country".

Simulate keyboard input

Objects can be used keyboardto simulate keyboard input. For example:

await page.keyboard.type('hello')

This code will enter the "hello" text into the currently focused element.

Simulate mouse operations

Objects can be used mouseto simulate mouse actions. For example:

await page.mouse.click(100, 100)

This code will click the mouse at a location on the screen where the x coordinate is 100 and the y coordinate is 100.

Page interaction with Playwright

Using Playwright can facilitate page interaction, which only requires the following steps:

  • Create a browser object:from playwright.sync_api import Playwright, sync_playwright_with_timeout; browser_type = sync_playwright_with_timeout().start().chromium; browser = browser_type.launch(headless=True)

  • Create a page object:page = browser.new_page()

  • Enter a page:page.goto('https://www.example.com')

  • Click on an element:page.click('#element-id')

  • Enter text:page.type('#input-id', 'text')

  • Pause execution:page.pause()

  • Close the browser:browser.close()

Actual demonstration

Here are some simple Playwright demo tutorials:

1. Open the browser

from playwright.sync_api import Playwright, sync_playwright_with_timeout
with sync_playwright_with_timeout() as playwright:
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto("https://www.google.com")
    print(page.title())
    browser.close()

This example demonstrates how to open the Chromium browser and open the Google homepage. headless=FalseThe parameter indicates to start the browser in a visible way.

2. Search keywords

from playwright.sync_api import Playwright, sync_playwright_with_timeout
with sync_playwright_with_timeout() as playwright:
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto("https://www.google.com")
    page.fill('input[name="q"]', "Python Playwright")
    page.press('input[name="q"]', "Enter")
    results = page.wait_for_selector("#search")
    print(results.text_content())
    browser.close()

This example demonstrates how to search keywords and get search results. page.fill()The and page.press()method are used to input and submit keywords in the search box, and page.wait_for_selector()the method is used to wait for the search result page to be loaded and return the result element. results.text_content()Returns the text content of the search results.

3. Screenshot

from playwright.sync_api import Playwright, sync_playwright_with_timeout
with sync_playwright_with_timeout() as playwright:
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto("https://www.google.com")
    page.screenshot(path="google.png")
    browser.close()

This example demonstrates how to take a screenshot of the opened page. page.screenshot()The method is used to take a screenshot of the page and save it to the specified path.

These are some simple Demo tutorials of Playwright that can help you understand the basic usage of Playwright. For more advanced usage, please refer to Playwright's official documentation: https://playwright.dev/docs/

4. Multiple page jumps

This demo shows how to navigate between multiple pages, such as jumping to another page after logging in.

import asyncio
from playwright.async_api import Playwright, async_playwright

async def navigate_to_another_page(playwright: Playwright):
    # 启动浏览器
    browser = await playwright.chromium.launch(headless=False)
    page = await browser.new_page()

    # 打开第一个页面
    await page.goto('https://example.com')

    # 在第一个页面上点击链接
    await page.click('a')
    # 等待页面加载完成
    await page.wait_for_selector('#second-page')

    # 获取新页面
    pages = await browser.pages()
    new_page = pages[-1]

    # 在新页面上执行操作
    await new_page.fill('#username', 'John Doe')
    await new_page.fill('#password', 'password')
    await new_page.click('#login')

    # 关闭浏览器
    await browser.close()

async with async_playwright() as playwright:
    asyncio.run(navigate_to_another_page(playwright))

4. File upload

This Demo shows how to simulate file upload in Playwright, such as uploading files in a form.

import asyncio
from pathlib import Path
from playwright.async_api import Playwright, async_playwright

async def upload_file(playwright: Playwright):
    # 启动浏览器
    browser = await playwright.chromium.launch(headless=False)
    page = await browser.new_page()

    # 打开上传页面
    await page.goto('https://example.com/upload')

    # 选择文件并上传
    file_path = Path('/path/to/file')
    input_element = await page.query_selector('input[type=file]')
    await input_element.set_input_files(str(file_path))
    await page.click('input[type=submit]')

    # 等待页面加载完成
    await page.wait_for_selector('#upload-success')

    # 关闭浏览器
    await browser.close()

async with async_playwright() as playwright:
    asyncio.run(upload_file(playwright))

5. Simulate mobile devices

This Demo shows how to simulate mobile devices in Playwright, such as running tests on mobile browsers.

import asyncio
from playwright.async_api import Playwright, async_playwright

async def simulate_mobile_device(playwright: Playwright):
    # 启动浏览器
    browser = await playwright.chromium.launch(headless=False)
    context = await browser.new_context(
        **playwright.devices['iPhone 11 Pro'],
        viewport=playwright.devices['iPhone 11 Pro']['viewport']
    )
    page = await context.new_page()

    # 在手机浏览器上打开页面
    await page.goto('https://example.com')

    # 在手机浏览器上执行操作
    await page.fill('#username', 'John Doe')
    await page.fill('#password', 'password')
    await page.click('#login')

    # 关闭浏览器
    await browser.close()

async with async_playwright() as playwright:
    asyncio.run(simulate_mobile_device(playwright))

6. Automated screenshots

It is very convenient to use Playwright to automate screenshots, and only need the following steps:

  • Install Playwright:pip install playwright
  • Create a browser object:from playwright.sync_api import Playwright, sync_playwright_with_timeout; browser_type = sync_playwright_with_timeout().start().chromium; browser = browser_type.launch(headless=True)
  • Create a page object:page = browser.new_page()
  • Enter a page:page.goto('https://www.example.com')
  • Capture the entire page:page.screenshot(path='example.png')
  • Close the browser:browser.close()

Full code example:

from playwright.sync_api import Playwright, sync_playwright_with_timeout
# 启动浏览器
browser_type = sync_playwright_with_timeout().start().chromium
browser = browser_type.launch(headless=True)

# 创建页面对象
page = browser.new_page()

# 进入页面并截图
page.goto('https://www.example.com')
page.screenshot(path='example.png')

# 关闭浏览器
browser.close()

7. Use Playwright for form filling and submission

Using Playwright can easily fill in and submit forms, and only need the following steps:

  • Create a browser object:from playwright.sync_api import Playwright, sync_playwright_with_timeout; browser_type = sync_playwright_with_timeout().start().chromium; browser = browser_type.launch(headless=True)
  • Create a page object:page = browser.new_page()
  • Enter a page:page.goto('https://www.example.com')
  • Fill out the form:page.fill('#username', 'myusername')
  • submit Form:page.click('button[type="submit"]')
  • Close the browser:browser.close()

Full code example:

from playwright.sync_api import Playwright, sync_playwright_with_timeout

# 启动浏览器
browser_type = sync_playwright_with_timeout().start().chromium
browser = browser_type.launch(headless=True)

# 创建页面对象
page = browser.new_page()

# 进入页面并填写表单
page.goto('https://www.example.com')
page.fill('#username', 'myusername')

# 提交表单
page.click('button[type="submit"]')

# 关闭浏览器
browser.close()

Supplementary summary

1. Use Playwright's recording function to automatically generate test scripts.

Playwright provides a recording tool that can perform some operations in the browser and automatically generate test scripts, which can greatly reduce the time and effort of writing test scripts. For specific usage methods, please refer to Playwright official documentation.

2. Use Playwright's built-in screenshot function to capture screenshots during the test.

Playwright provides a built-in screenshot function that can capture screenshots at any time during the test process to facilitate subsequent problem analysis and troubleshooting. For specific usage methods, please refer to Playwright official documentation.

3. Use Playwright’s multi-language support, such as Python, Java, C#, etc.

Playwright provides multi-language support, so you can write test scripts in the programming language you are most familiar with, such as Python, Java, C#, etc. For specific usage methods, please refer to the corresponding language documentation in Playwright official documentation.

4. Use Playwright’s multi-browser support, such as Chrome, Firefox, Edge, etc.

Playwright provides multi-browser support, you can use multiple browsers to execute test scripts, such as Chrome, Firefox, Edge, etc. For specific usage methods, please refer to Playwright official documentation.

5. Use Playwright's headless mode to run test scripts in a headless browser.

Playwright provides a headless mode, which can run test scripts in a browser without an interface, which can greatly improve test efficiency and reduce resource consumption for running test scripts. For specific usage methods, please refer to Playwright official documentation.

6. Use Playwright's network interception function to simulate different network environments and test network requests.

Playwright provides network interception function, which can simulate different network environments and test network requests, such as simulating slow network, simulating request failure, etc. For specific usage methods, please refer to Playwright official documentation.

7. Use Playwright's multi-page support to test complex multi-page applications.

Playwright provides multi-page support to test complex multi-page applications, such as cross-page interactions, navigation between pages, etc. For specific usage methods, please refer to Playwright official documentation.

Guess you like

Origin blog.csdn.net/qq_46158060/article/details/130621770