Video Recording in Playwright

In Playwright Java, video recording is a feature that allows you to capture the execution of your automated browser test sessions in the form of video files. This is particularly useful for debugging, reporting, and understanding the behavior of your test scripts when they run.

Purpose:

Video recording helps testers analyze the test flow, identify failures, and verify that actions were performed as intended. Instead of only relying on logs or screenshots, a full playback video gives complete visibility of the user journey.

How It Works:

Playwright provides video recording capabilities at the context level (BrowserContext). When a new browser context is created, you can enable video recording for all pages that belong to that context. Each video records the actions performed in its corresponding page session.

Storage of Videos:

The recorded videos are typically stored in a specified directory on the local system. After test execution, the video files can be retrieved and saved for later inspection. The storage location can be configured when setting up the context.

Format:

Videos are generally saved in .webm format, which is lightweight and compatible with most browsers and media players.


Use Cases:

  • Debugging Failures – When a test fails, you can watch the recording to see the sequence of actions that led to the failure.
  • Documentation – Videos can be shared with developers, QA teams, or stakeholders to demonstrate test execution.
  • Regression Testing – Helps in validating that new changes have not broken the existing flow by visually confirming execution steps.

Integration with Reporting Tools:

The recorded videos can also be attached to automated test reports, making them valuable for test evidence in Continuous Integration/Continuous Deployment (CI/CD) pipelines.

In Playwright Java, you can perform video recording of your browser session by enabling video recording in the browser context options. Playwright will save the video of each page created from that context.
















Steps to Record Video in Playwright Java:

  • Create a directory where video recordings will be saved.
  • Configure the context using Browser.NewContextOptions() and enable video recording.
  • Perform browser actions.
  • Close the page and context to ensure the video is saved.

Website to be automate: https://example.com












Code Example: Record Video in Playwright Java


import com.microsoft.playwright.*;

import java.nio.file.Paths;

public class VideoRecordingExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            // Launch browser
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // Set video recording options
            Browser.NewContextOptions contextOptions = new Browser.NewContextOptions()
                    .setRecordVideoDir(Paths.get("videos/"))  // Directory to save videos
                    .setRecordVideoSize(1280, 720);          // Optional: set video resolution

            // Create browser context with video recording
            BrowserContext context = browser.newContext(contextOptions);

            // Create a new page (video recording will start)
            Page page = context.newPage();

            // Navigate to a website
            page.navigate("https://example.com");

            // Perform some actions
            page.click("text=More information"); // Adjust if element exists

            // Wait for a while (simulate some user interaction time)
            page.waitForTimeout(3000);

            // Close page and context (this will save the video)
            page.close();
            context.close();

            System.out.println("Video saved in: videos/ directory");
        }
    }
}


Code explanation:

(a) Launch browser
(b) Set video recording options by setRecordVideoDir() and setRecordVideoSize()         methods
(c) Create BrowserContext object
(d) Create Page object
(e) Navigate to the website
(f) Perform some actions on html web elements


Code snippet responsible to record and store videos






Videos folder in Project Structure











Important Points:
  • Make sure videos/directory is writeable.
  • Video is finalized only when the page or context is closed.
  • You can customize file name using recordVideoDir and managing output.

How to Show Visible Elements in Playwright


What are Visible Elements?

In web automation, a visible element is an element that is actually displayed on the web page and can be seen or interacted with by the user.

An element may exist in the DOM (Document Object Model) but still not be visible. For example:

  • It may be hidden using CSS (display:none, visibility:hidden, or opacity:0).
  • It may be outside the current viewport (scrolled out of view).
  • It may be overlapped by another element.
  • It may not yet be rendered because of delayed loading or dynamic conditions.

 

Why Visibility Matters in Playwright?

  • Playwright ensures realistic testing: it doesn’t just check if an element exists in the DOM, but also if it is visible for interaction.
  • Actions like click, fill, or type only work on visible elements (to simulate real user behavior).
  • This helps avoid false positives in test automation, where a script might interact with hidden elements that a real user cannot.

When you want to show or check visible elements in Playwright, the goal is to filter or interact only with the elements that are currently visible on the page. Here’s how it works in theory:


Locating Elements
  • You start by locating elements using selectors (like buttons, links, rows, etc.)
  • This might return multiple elements (some visible, some hidden).

Filtering Visible Ones
  • Playwright allows filtering the located elements so only the visible ones are considered.
  • This ensures your script only interacts with those elements that a real user can see.

Extracting Visible Elements
  • Once filtered, you can fetch the text, attributes, or other properties of the visible elements.
  • For example, if you have a menu with hidden dropdown options, Playwright can extract only the items that are currently shown.

Using Visibility for Assertions
  • You can verify if a particular element is visible at a given time (for example, a success message should be visible after form submission).
  • This ensures UI behavior matches expected user experience.

Debugging / Displaying Visible Elements
  • Sometimes testers print or log the list of visible elements (like all visible links or buttons).
  • This helps confirm that the UI is rendering the expected items.

To show all visible elements on a web page using Playwright Java, you can:

  • Use a general selector like "*" to target all elements.
  • Filter them using elementHandle.isVisibleAsync().













Here’s how you can do it with Playwright Java, using 

https://example.com for demonstration:









Java Code: Show All Visible Elements on a Webpage

import com.microsoft.playwright.*;

public class VisibleElementsExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Navigate to a sample website
            page.navigate("https://example.com");

            // Get all elements on the page using the universal selector '*'
            Locator allElements = page.locator("*");

            int count = allElements.count();
            System.out.println("Total Elements Found: " + count);
            System.out.println("Visible Elements:");

            for (int i = 0; i < count; i++) {
                Locator element = allElements.nth(i);
                if (element.isVisible()) {
                    System.out.println("Tag: " + element.evaluate("el => el.tagName") +
                            ", Text: " + element.innerText().trim());
                }
            }

            browser.close();
        }
    }
}

Code explanation:

(a) Navigate to website by page.vavigate()
(b) Get all elements on the page by using page.locator("*")
(c) Count all web elements by allElements.count();
(d) Iterate all web elements by using for loop and display on console.


Please Note:
  • page.locator("*"): Selects all elements.
  • element.isVisible(): Filters only visible elements.
  • element.evaluate("el => el.tagName"): Fetches tag name using JavaScript.
  • element.innerText(): Gets the visible text content of the element.


Suggested Posts:

1. BrowserContext in Playwright
2. File Upload in Playwright
3. Comma Selectors in Playwright
4. Trace Viewer in Playwright
5. Page Object Model in Playwright