Playwright Python Tutorial: Step-by-Step Guide (2026) | TechSarvam

1. Introduction to Playwright Python

Playwright is a modern browser automation framework used to test web applications across different browsers. It supports Chromium, Firefox, and WebKit and provides powerful features for automating real user interactions.

A Playwright Python tutorial helps beginners and QA Automation Engineers understand how to build automated browser tests using Python.

For example, consider an online shopping application. A tester needs to verify login, product search, adding products to the cart, and checkout functionality. Instead of performing these activities manually, Playwright can automate the complete workflow.

Using Playwright with Python, you can:

In this Playwright Python tutorial guide, we will start with installation and gradually build a practical automation framework using Pytest, fixtures, Page Object Model, and CI/CD integration.

2. What Is Playwright and Why Use Python?

Playwright is an open-source automation framework developed by Microsoft. It allows developers and testers to automate web applications using JavaScript, TypeScript, Python, Java, and .NET.

Python is a popular programming language because of its readable syntax and extensive automation ecosystem.

Benefits of Playwright Python

1. Cross-browser support

Playwright supports Chromium, Firefox, and WebKit. You can execute the same test scenarios across multiple browser engines.

2. Automatic waiting

Playwright automatically waits for elements to become actionable before performing operations.

3. Easy Python integration

You can use Python functions, classes, modules, and packages to create reusable automation scripts.

4. Pytest support

Playwright integrates with Pytest, allowing testers to use fixtures, hooks, parameterization, and test markers.

5. Powerful debugging

You can capture screenshots, record traces, inspect browser actions, and analyze failed tests.

6. CI/CD integration

Playwright tests can execute automatically through GitHub Actions and Jenkins.

These capabilities make Playwright Python suitable for beginners and experienced QA engineers.

3. Prerequisites and Python Environment Setup

Before starting this Playwright Python tutorial for beginners, install the required tools.

Install Python

Download Python from:

https://www.python.org/downloads

Install a supported Python 3 version.

Verify the installation:

python –version

Check pip:

pip –version

Install Visual Studio Code

Download VS Code:

https://code.visualstudio.com

Recommended extensions:

  • Python.
  • Pylance.
  • Python Debugger.

You should understand basic Python concepts such as variables, functions, classes, dictionaries, lists, and exception handling.

Create a Project Folder

Open your terminal:

mkdir playwright-python-tutorial

cd playwright-python-tutorial

Create a Virtual Environment

For Windows:

python -m venv venv

venv\Scripts\activate

For macOS or Linux:

python3 -m venv venv

source venv/bin/activate

A virtual environment keeps project dependencies separate from other Python applications.

4. Installing Playwright and Browser Binaries

Playwright provides a Python package that supports browser automation.

For this tutorial, we will use Playwright with Pytest.

Step 1: Install Playwright and Pytest

Execute:

pip install pytest pytest-playwright

The pytest-playwright package provides integration between Playwright and Pytest.

Step 2: Install Browser Binaries

Execute:

playwright install

This installs the browser binaries required by Playwright.

To install only Chromium:

playwright install chromium

To install Firefox:

playwright install firefox

To install WebKit:

playwright install webkit

Step 3: Verify Installation

Execute:

pytest –version

playwright –version

If both commands execute successfully, the basic environment is ready.

5. Creating a Python Project and Folder Structure

A structured project helps maintain automation scripts as the number of test cases increases.

Recommended folder structure:

playwright-python-tutorial/

│

├── tests/

│   ├── test_homepage.py

│   ├── test_login.py

│   └── test_search.py

│

├── pages/

│   ├── home_page.py

│   └── login_page.py

│

├── test_data/

│   └── testdata.json

│

├── utils/

│   └── helpers.py

│

├── conftest.py

├── pytest.ini

├── requirements.txt

└── .gitignore

Explanation:

Folder or filePurpose
testsContains test cases.
pagesContains Page Object Model classes.
test_dataStores test data.
utilsContains reusable helper functions.
conftest.pyDefines shared fixtures and hooks.
pytest.iniStores Pytest configuration.
requirements.txtLists Python dependencies.
.gitignoreExcludes unnecessary files from Git.

Save project dependencies:

pip freeze > requirements.txt

Install them later using:

pip install -r requirements.txt

6. Writing and Running Your First Playwright Test

Let’s create a simple test that opens the Playwright documentation website and verifies its title.

Create tests/test_homepage.py:

from playwright.sync_api import Page, expect

def test_homepage(page: Page):

    page.goto(“https://playwright.dev”)

    expect(page).to_have_title(

        “Fast and reliable end-to-end testing for modern web apps | Playwright

    )

    expect(

        page.get_by_role(“link”, name=”Get started”)

    ).to_be_visible()

Understanding the Code

  • Page represents a browser tab.
  • page.goto() navigates to the website.
  • expect() validates the expected result.
  • get_by_role() locates an element using its accessible role.
  • to_be_visible() verifies element visibility.

The page fixture is provided automatically by the Pytest Playwright plugin.

Execute Your Test

Run all tests:

pytest

Run a specific test file:

pytest tests/test_homepage.py

Run tests with detailed output:

pytest -v

Run tests with additional print statements:

pytest -s

You have successfully created your first Playwright Python test.

7. Locators, Browser Actions, and Assertions

Locators identify web elements that automation scripts need to interact with.

Playwright provides several locator methods.

LocatorPurpose
get_by_role()Locates elements using accessible roles.
get_by_text()Locates elements using visible text.
get_by_label()Locates form controls using labels.
get_by_placeholder()Locates input fields using placeholders.
get_by_test_id()Locates elements using test IDs.
locator()Uses CSS, XPath, and other supported selectors.

Practical Example: Login Form

from playwright.sync_api import Page, expect

def test_login(page: Page):

    page.goto(“https://example.com/login”)

    page.get_by_label(“Username”).fill(“testuser”)

    page.get_by_label(“Password”).fill(“password123”)

    page.get_by_role(“button”, name=”Login”).click()

    expect(

        page.get_by_text(“Welcome”)

    ).to_be_visible()

This is an illustrative example. Replace the URL, form labels, credentials, and expected message with those of your application.

Common Browser Actions

Click a button:

page.get_by_role(“button”, name=”Submit”).click()

Enter text:

page.get_by_placeholder(“Enter name”).fill(“Rahul”)

Select a dropdown option:

page.locator(“#country”).select_option(“India”)

Check a checkbox:

page.get_by_label(“Accept Terms”).check()

Upload a file:

page.get_by_label(“Upload document”).set_input_files(

    “test_data/sample.pdf”

)

Assertions

Assertions verify whether an application behaves as expected.

expect(page).to_have_title(“Dashboard”)

expect(page).to_have_url(

    “https://example.com/dashboard”

)

expect(

    page.get_by_text(“Welcome”)

).to_be_visible()

expect(

    page.get_by_role(“button”, name=”Submit”)

).to_be_enabled()

Prefer Playwright’s web-first assertions because they automatically retry until the expected condition is satisfied or the timeout is reached.

8. Handling Waits and Dynamic Web Elements

Modern web applications frequently update their content dynamically using JavaScript.

For example, a product search may display results only after the backend returns information.

Playwright handles many synchronization requirements automatically.

Automatic Waiting

page.get_by_role(

    “button”,

    name=”Search”

).click()

Playwright waits for the button to become actionable before clicking it.

Waiting for an Element

page.get_by_text(“Search results”).wait_for(

    state=”visible”

)

Waiting for a URL

page.wait_for_url(“**/dashboard”)

Waiting for a Response

with page.expect_response(

    lambda response: “/api/products” in response.url

) as response_info:

    page.get_by_role(

        “button”,

        name=”Search”

    ).click()

response = response_info.value

assert response.status == 200

This is useful when you need to verify network activity triggered by a browser action.

Avoid unnecessary fixed waits such as:

page.wait_for_timeout(5000)

Condition-based waiting makes tests faster and more reliable.

9. Using Playwright with Pytest, Fixtures, and Hooks

Pytest is a popular Python test runner that helps organize and execute automated test scripts.

The Playwright Pytest plugin provides built-in fixtures.

Common Fixtures

FixturePurpose
pageProvides a browser page.
contextProvides an isolated browser context.
browserProvides a browser instance.
browser_nameProvides the selected browser name.

Create a Custom Fixture

Create conftest.py:

import pytest

@pytest.fixture

def base_url():

    return “https://playwright.dev”

@pytest.fixture

def open_homepage(page, base_url):

    page.goto(base_url)

    return page

Use this fixture in your test:

from playwright.sync_api import expect

def test_homepage_title(open_homepage):

    expect(open_homepage).to_have_title(

        “Fast and reliable end-to-end testing for modern web apps | Playwright”

    )

The custom fixture opens the homepage before the test executes.

Pytest Hooks

Hooks allow you to customize test execution.

Example:

def pytest_runtest_setup(item):

    print(f”Starting test: {item.name}”)

This hook executes before the setup phase of each test.

Hooks can be used for logging, reporting, and other execution-related operations.

Pytest Configuration

Create pytest.ini:

[pytest]

testpaths = tests

addopts = -v

python_files = test_*.py

This configuration tells Pytest where to find test files and how to execute them.

10. Synchronous and Asynchronous Playwright APIs

Playwright Python supports two API styles: synchronous and asynchronous.

Synchronous API

The synchronous API is beginner-friendly because operations execute in a straightforward sequence.

from playwright.sync_api import sync_playwright

with sync_playwright() as p:

    browser = p.chromium.launch(headless=True)

    page = browser.new_page()

    page.goto(“https://playwright.dev”)

    print(page.title())

    browser.close()

You do not need to use await with synchronous methods.

Asynchronous API

The asynchronous API uses Python’s async and await keywords.

import asyncio

from playwright.async_api import async_playwright

async def main():

    async with async_playwright() as p:

        browser = await p.chromium.launch(

            headless=True

        )

        page = await browser.new_page()

        await page.goto(“https://playwright.dev”)

        print(await page.title())

        await browser.close()

asyncio.run(main())

Difference Between Sync and Async

SynchronousAsynchronous
Uses sync_playwright()Uses async_playwright()
Normal Python functionsUses async def
No await requiredUses await
Easier for beginnersUseful for asynchronous workflows

Both APIs support browser automation. Do not mix them within the same workflow.

For beginners using Pytest, synchronous Playwright is a practical starting point.

11. Page Object Model and Reusable Framework Development

Page Object Model is a design pattern that separates page locators and actions from test cases.

It helps reduce duplicate code and improves framework maintenance.

Create a Page Object Class

Create pages/home_page.py:

class HomePage:

    def __init__(self, page):

        self.page = page

        self.get_started = page.get_by_role(

            “link”,

            name=”Get started”

        )

    def open(self):

        self.page.goto(“https://playwright.dev”)

    def click_get_started(self):

        self.get_started.click()

Create a Test Using POM

Create tests/test_navigation.py:

from playwright.sync_api import expect

from pages.home_page import HomePage

def test_navigation(page):

    home = HomePage(page)

    home.open()

    home.click_get_started()

    expect(page).to_have_url(

        “https://playwright.dev/docs/intro”

    )

This test uses the HomePage class instead of directly defining page locators.

Benefits of Page Object Model

  • Improves code reusability.
  • Reduces duplicate locators.
  • Makes maintenance easier.
  • Separates business logic from test logic.
  • Supports larger automation frameworks.

For enterprise projects, combine POM with fixtures, test data management, and environment configurations.

12. Screenshots, Reports, Debugging, and Cross-Browser Testing

Playwright provides useful debugging and reporting capabilities.

Capture Screenshots

page.screenshot(

    path=”homepage.png”,

    full_page=True

)

You can configure automatic screenshots through the Pytest plugin:

pytest –screenshot only-on-failure

Generate HTML Reports

Install pytest-html:

pip install pytest-html

Execute:

pytest –html=report.html –self-contained-html

This generates an HTML report containing test execution results.

Debug Tests

Run:

PWDEBUG=1 pytest -s

On Windows PowerShell:

$env:PWDEBUG=”1″

pytest -s

You can also pause execution using:

page.pause()

This opens Playwright Inspector in a suitable headed debugging session.

Trace Viewer

Execute tests with tracing:

pytest –tracing retain-on-failure

Open a trace file:

playwright show-trace trace.zip

Trace Viewer helps analyze browser actions, network activity, screenshots, and test execution details.

Cross-Browser Testing

Playwright supports Chromium, Firefox, and WebKit.

Execute tests using Chromium:

pytest –browser chromium

Execute tests using Firefox:

pytest –browser firefox

Execute tests using WebKit:

pytest –browser webkit

Execute the same tests across all three:

pytest –browser chromium –browser firefox –browser webkit

Install the corresponding browser binaries before execution.

13. GitHub Actions and Jenkins CI/CD Integration

Continuous integration helps execute automated tests whenever developers push code or create pull requests.

GitHub Actions Integration

Create:

.github/workflows/playwright-python.yml

name: Playwright Python Tests

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – name: Checkout

        uses: actions/checkout@v4

      – name: Setup Python

        uses: actions/setup-python@v5

        with:

          python-version: “3.12”

      – name: Install dependencies

        run: |

          pip install -r requirements.txt

      – name: Install browsers

        run: |

          playwright install –with-deps

      – name: Run tests

        run: |

          pytest –html=report.html –self-contained-html

      – name: Upload report

        if: always()

        uses: actions/upload-artifact@v4

        with:

          name: playwright-report

          path: report.html

This pipeline checks out the code, installs Python dependencies and browsers, executes tests, and uploads the report.

For production repositories, review and pin GitHub Actions to approved versions or commit SHAs.

Jenkins Integration

Create a Jenkinsfile:

pipeline {

    agent any

    stages {

        stage(‘Checkout’) {

            steps {

                checkout scm

            }

        }

        stage(‘Install Dependencies’) {

            steps {

                sh ‘pip install -r requirements.txt’

            }

        }

        stage(‘Install Browsers’) {

            steps {

                sh ‘playwright install –with-deps chromium’

            }

        }

        stage(‘Run Tests’) {

            steps {

                sh ‘pytest –html=report.html –self-contained-html’

            }

        }

    }

    post {

        always {

            archiveArtifacts artifacts: ‘report.html’,

                             allowEmptyArchive: true

        }

    }

}

The Jenkins agent should have a compatible Python environment and the required operating-system dependencies.

14. Common Errors, Troubleshooting, and Best Practices

ErrorSolution
Python is not recognizedInstall Python and configure PATH.
No module named playwrightInstall the Playwright package.
Browser executable not foundExecute playwright install.
Pytest command not foundActivate the virtual environment and install Pytest.
Element not foundVerify the locator and application state.
Timeout exceededCheck application availability and element conditions.
Import errorVerify Python package and folder structure.
Tests fail in CICheck browser dependencies and Python versions.

Best Practices

  1. Use virtual environments.
  2. Organize tests into meaningful modules.
  3. Use reusable fixtures.
  4. Follow Page Object Model for larger frameworks.
  5. Prefer accessible, user-facing locators.
  6. Avoid unnecessary fixed waits.
  7. Use screenshots and traces to investigate failures.
  8. Separate test data from test scripts.
  9. Store credentials in environment variables or CI secrets.
  10. Execute tests across multiple browsers when required.
  11. Integrate tests with continuous integration.
  12. Keep dependencies compatible.

Interview Tips for Indian QA Engineers and SDETs

Prepare practical explanations for these common interview topics:

Build a project demonstrating login, search, navigation, assertions, reusable methods, and CI/CD. Being able to explain your implementation is especially useful during SDET and QA Automation interviews.

15. Frequently Asked Questions

1. What is Playwright Python tutorial?

A Playwright Python tutorial is a practical learning guide that explains how to install Playwright, automate browsers, create test cases, validate application behaviour, and build automation frameworks using Python.

2. What are the benefits of Playwright Python tutorial?

Learning Playwright Python helps QA engineers understand browser automation, cross-browser testing, automatic waiting, Pytest integration, reporting, debugging, and CI/CD.

3. How do I get started with Playwright Python tutorial?

Install Python, create a virtual environment, install pytest-playwright, execute playwright install, and create your first test using the Pytest page fixture.

4. Is Playwright Python suitable for beginners?

Yes. Beginners with basic Python knowledge can start with synchronous Playwright and gradually learn Pytest, fixtures, and Page Object Model.

5. Does Playwright Python support multiple browsers?

Yes. Playwright supports Chromium, Firefox, and WebKit. The same test scenarios can be executed across these browser engines.

6. Can I use Pytest with Playwright Python?

Yes. The pytest-playwright package provides fixtures and integration for running browser automation tests through Pytest.

7. Can Playwright Python be integrated with Jenkins?

Yes. Jenkins can install Python dependencies, download browser binaries, execute Pytest scripts, and archive HTML reports through a pipeline.

Leave a Comment

Your email address will not be published. Required fields are marked *