# Playwright and Selenium

Browser automation frameworks that drive a real browser to exercise an application as a user would.

**Stands alone:** nothing in the curriculum requires this first, and nothing yet builds on it.

*Software Engineering · Software Testing*


## Why learn this

This allows you to test software exactly as a real person experiences it. You will learn to write code that controls a real web browser, clicking buttons and filling forms automatically. This is essential for verifying that the visible parts of an application work correctly together. It also introduces the technology behind AI agents that can browse the web on your behalf, understanding how they 'see' and interact with pages.


## The intuition

Imagine you are checking a website for errors before launch. You have a list of things to verify: clicking 'Sign Up' must lead to a registration page, entering an email must create an account, and so on. Doing this manually is slow and prone to human error. Instead, you write instructions that tell a browser to perform these actions automatically. These instructions can run thousands of times across different browsers to ensure nothing breaks. Playwright and Selenium are the tools that act as the 'remote control' for your browser, executing your written instructions precisely.


## An analogy

Think of learning to drive a car with an instructor sitting in the passenger seat. The browser is the car, and the code you write is your driving plan. Selenium is like having an instructor who only nudges the steering wheel gently; you must constantly check if the car is going where you want and correct course yourself. Playwright is like having an advanced autopilot system; you tell it 'drive to the store,' and it handles steering, stopping for traffic, and parking automatically, ensuring you arrive safely without needing constant manual checks. This reliability removes the frustration of tests failing just because a button appeared one second late, which happens when the browser is still loading. The limitation is that unlike a car with fixed wheels, a website can look different on a phone versus a desktop, so you must test both sizes.


## Definition

Browser automation frameworks are tools that use code to control a real web browser, allowing you to perform user actions like clicking and typing automatically to verify that an application works correctly from start to finish. They serve as the foundation for end-to-end testing and the underlying mechanics of AI browsing agents.


## How it connects

This sits alongside unit testing, which is checking individual small parts of code in isolation, and integration testing, which checks how those parts work together. While those methods are faster and catch logic errors early, this approach tests the visible interface that users actually touch. It also relates to API testing, which verifies the data exchange between systems behind the scenes; while API tests prove the backend works, browser automation proves the user sees the correct result.


## The mathematics

This concept doesn't rely heavily on mathematics, but it uses the idea of *logic* and *conditions* — the language of programming. When you write a test, you often need to say: 'If element A is visible, then click it; otherwise, log an error.' That's a conditional branch. Also, you may need to loop: 'For each item in a list, do the same action.' That's iteration. These are not complex formulas but rather structured ways of making decisions. The only 'mathematics' is the idea of *truth values* — things are either True or False. You check if an element is present, and based on that (True/False) you choose a path. There are no equations, but the logical operations (AND, OR, NOT) are the building blocks. For example, you might wait for both a button to be visible AND a specific text to appear before continuing. That's a logical AND. The mathematics section will introduce loops and conditionals as foundational programming constructs.

No algebraic formula is needed, but the logic can be expressed as: for each element in a collection, perform an action if a condition holds. This is the loop-and-condition pattern. Symbolically: for i in range(n): if condition(i): do_action(i). The 'range(n)' is the loop, 'if' is the condition, and 'do_action' is the action. This is a programming pattern, not a math formula.


## A worked example

```
Imagine you have a list of item names on a shopping website: ["apple", "banana", "cherry"]. You want to verify that each item appears on the page. The count of items is 3. Let's step through how a loop would work.

Step 1: Start with index = 0, item = list[0] = 'apple'   # We check the first item.
Step 2: Is 'apple' on the page? Yes → continue.   # We have a condition: if the text is found, we move to the next item.
Step 3: index = 1, item = list[1] = 'banana'   # We move to the second item.
Step 4: Is 'banana' on the page? No → report failure.   # If any item is missing, we stop and say the test fails.

Result: The loop runs until all items are checked. If all are present, the test passes. Here, the test would fail because 'banana' is missing.
```


## From scratch, in Python

```python
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)  # Show the browser
    page = browser.new_page()
    page.goto("https://example.com")
    page.click("button#submit")
    page.fill("#username", "testuser")
    page.type("#password", "secret123")
    page.press("button#login", "Enter")
    if "Welcome" in page.content():
        print("Login successful")
    else:
        print("Login failed")
    browser.close()
```


## The same thing, with a framework

```python
Playwright and Selenium are the frameworks themselves; there is no higher-level library needed. However, Selenium has a similar structure using WebDriver. The underlying operations are exactly what you would do manually: launch a browser, navigate, interact, read the page, close.
```


## What the code does

First, we import `sync_playwright` – the control interface. Inside a `with` block (which ensures the browser is closed even if errors occur), we launch a browser (Chromium). We create a `page` object representing a tab. `page.goto()` navigates to a URL. `page.click()` clicks an element (using a CSS selector like `button#submit`). `page.fill()` types text into an input field. `page.type()` simulates typing keystroke by keystroke (useful for testing search autocomplete). `page.press()` sends a keyboard key like Enter. Then we check `page.content()` – the full HTML – to see if it contains 'Welcome', and print the result. Finally, we close the browser. Every step requires the page to be 'ready' – Playwright automatically waits for elements to be actionable, which is the 'auto-waiting' feature. Selenium often requires manual `WebDriverWait` calls.


## Common misconceptions

**Automation frameworks are just schedulers that click a button** — I can write a script that clicks a button at a certain time, and that's enough.

They don't just click; they interact with the browser's DOM, manage page loads, handle pop-ups, and wait for conditions. Clicking at a fixed time often fails because the page hasn't loaded. In fact: They control the full browser lifecycle: navigation, user interaction, state verification, and they do so conditionally based on the page state.

**Selenium and Playwright are the same** — They are two different brands of the same thing, so I can use either without changing my approach.

They have different APIs, different levels of auto-waiting, and different browser support. Playwright has built-in waiting and is faster, while Selenium is more language-agnostic. In fact: Both are frameworks for driving browsers, but Playwright offers more modern features like auto-waiting, network interception, and mobile emulation out of the box.

**Automated tests replace manual testing entirely** — If I automate all UI tests, I don't need a human to test anything.

Automated tests only check what you script. They can't explore, they can't notice subtle visual differences, and they often miss accessibility issues. In fact: Automation complements manual/exploratory testing. The pyramid suggests few e2e tests, relying on lower levels for coverage.

**End-to-end tests are the most important and should be numerous** — If I have many end-to-end tests, I'm safer.

They are slow and brittle. Running thousands of them takes forever and they fail for trivial reasons. The library says 'keep them few'. In fact: Use a few critical end-to-end journeys, and rely on broader unit and integration tests for speed and stability.


## In short

Browser automation frameworks (Playwright and Selenium) drive a real browser to test a web application as a user would. Key takeaways: Playwright offers auto-waiting, reducing flakiness; keep end-to-end tests few; and these same drivers power AI web agents, making them essential for both testing and modern AI tool use.


## Where this is used

Where is this used in building AI systems? The library notes 'The same drivers now back agentic browser automation.' Here's the mechanism: You have an AI agent (like a language model) that decides to accomplish a task on a website. Instead of the agent knowing HTML, it uses a framework like Playwright to control a browser. For example, an agentic system for travel booking might issue commands like: 'Navigate to expedia.com, click on Flights, fill in the origin and destination, click Search.' The agent generates these commands, and the framework executes them. This is how modern 'AI web agents' work. In large language models, this is often used to create 'tool use' – the LLM is trained on how to call functions that perform browser actions. In retrieval-augmented generation, if the system needs to fetch a page behind a login, it can use automation to log in. In small models running on devices, you might not have the full LLM but still have a lightweight agent that triggers a browser. In ordinary applied machine learning, browser automation is used for UI testing of ML-powered applications (like recommendation widgets). In practice, a developer writing a test with Playwright would write the code above; if the test fails, the framework takes a screenshot or video for debugging. When done badly – missing auto-waits – you get flaky tests that ruin trust. When done well, you get fast, reliable end-to-end verification.


---

Read this on the web: https://basavapurushottam.com/learn-ai/playwright-and-selenium
