Showing posts with label Browser Automation. Show all posts
Showing posts with label Browser Automation. Show all posts

Overview of Playwright Framework

 



What is Playwright?

Playwright is an open-source end-to-end (E2E) automation testing framework developed by Microsoft. It is used to automate modern web applications across multiple browsers and platforms. Playwright provides APIs for automating Chromium (Chrome, Edge), Firefox, and WebKit (Safari) browsers using a single codebase.










Key Features of Playwright


FeatureDescription
Cross-browser testingSupports Chromium, Firefox, and WebKit with a unified API.
Cross-platformRuns on Windows, Linux, and macOS.
Auto-waitAutomatically waits for elements to be ready before performing actions.
Headless & Headful modesCan run in the background (headless) or visible mode (headful).
Multiple language supportOfficial support for JavaScript/TypeScript, Python, Java, and .NET.
Built-in test runnerIncludes its own Playwright Test runner for powerful parallel execution, retries, and test reporting.
Browser contextsIsolates test environments within the same browser instance to simulate multiple users.
Network & Geolocation mockingAllows simulation of network conditions and geolocation.
Visual comparisonsSupports screenshot and video capturing for visual regression testing.

Supported Browsers

  • Chromium (Google Chrome, Microsoft Edge)
  • Firefox
  • WebKit (Safari)

These are bundled with Playwright, so no need to install them manually.


Advanced Features

  • API Testing: Playwright can make HTTP requests and validate responses.
  • Mobile Emulation: Emulates mobile devices like iPhone, Pixel.
  • Component Testing: React, Angular, Vue component testing support.
  • CI/CD Integration: Jenkins, GitHub Actions, GitLab, Azure DevOps, etc.


Comparison: Playwright vs Selenium

FeaturePlaywrightSelenium
Modern web supportExcellentLimited in modern web features
SpeedFasterSlower
Auto-waitYesManual wait often required
Browser supportChromium, Firefox, WebKitAll major browsers
API TestingBuilt-inNeeds external tools
Built-in test runnerYesNo



Playwright generally used for:

  • Cross-browser UI Testing
  • Visual Regression Testing
  • API Testing
  • CI/CD pipeline automation
  • Mobile and geolocation testing
  • Real-time network condition simulation

You can go official website for more detail: 
https://playwright.dev/java/










Suggested Posts:

1. Handle Alerts in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Token Based Authentication in Playwright
5. Basic Authentication in Playwright

Test Basic Authentication in API by Playwright




What is Basic authentication?

Basic Authentication is the process to verify a user by means of user's login credentials, it can be username and password. 


How Playwright Java Handles basic authentication?

Playwright provides a straightforward way to handle Basic Authentication by passing credentials when creating a BrowserContext.

  • A BrowserContext is like an isolated browser profile.
  • While creating the context, Playwright allows you to define HTTP credentials (username and password).
  • Once configured, every request made within that context automatically includes the necessary Authorization header, so you don’t need to manually handle it on each request.

Advantages of This Approach

  • No need to manually add headers for each request.
  • Works across all pages, frames, and API calls within the same context.
  • Ensures a secure and centralized way of handling credentials.















Steps:

  • Set up Playwright.
  • Create a new browser context with HTTP credentials.
  • Navigate to a website that requires basic authentication.
  • Assert the successful authentication.

We’ll use the website:
https://httpbin.org/basic-auth/user/passwd











It requires basic auth with:

  • Username: user

  • Password: passwd




Playwright Java Code Example:

import com.microsoft.playwright.*;

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

            // Set up HTTP Basic Auth credentials
            Browser.NewContextOptions contextOptions = new Browser.NewContextOptions()
                    .setHttpCredentials("user", "passwd");  // username: user, password: passwd

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

            // Open a new page
            Page page = context.newPage();

            // Navigate to the Basic Auth test URL
            page.navigate("https://httpbin.org/basic-auth/user/passwd");

            // Verify if authentication is successful
            String bodyText = page.textContent("body");
            if (bodyText.contains("\"authenticated\": true")) {
                System.out.println("Basic authentication successful!");
            } else {
                System.out.println("Basic authentication failed.");
            }

            // Close browser
            browser.close();
        }
    }
}



Code explanation:

(a) After creating Browser object, we have to setup HTTP basic auth credentials by setHttpCredentials()
(b) Create browser context with credentials
(c) Create Page object
(d) Navigate to the URL
(e) Verify if authentication is successful



Output:


Basic authentication successful!




Maven Dependencies:

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.44.0</version>
</dependency>

Automate Google.com by Playwright

 



To automate https://www.google.com using Playwright with Java, you can perform the following basic steps:


1. Set up Playwright Environment

  • First, you would need to install Playwright and configure it for your preferred programming language (Java, JavaScript/TypeScript, Python, etc.).
  • Playwright provides browsers like Chromium, Firefox, and WebKit, which can be used to open and interact with Google.

2. Launch the Browser
  • Playwright allows launching a browser instance in either headless mode (without GUI) or headed mode (with GUI).
  • For automation, you typically start a new browser session to ensure a clean state.
3. Create a Browser Context
  • A BrowserContext is like a separate user profile, with its own cookies, cache, and session data.
  • Using contexts helps in isolating tests so that actions on one context don’t affect another.
  • For example, if you open Google in one context, it won’t share login data with another context unless you configure it.
4. Navigate to Google.com
  • You instruct Playwright to open the URL https://www.google.com
  • Playwright waits until the page loads and becomes interactive.
5. Locate the Search Box
  • Playwright uses selectors (like CSS selectors, XPath, text selectors) to find elements on a page.
  • The Google search box is a standard input field, so automation involves locating it.
6. Type a Search Query
  • After finding the search box, Playwright can simulate user actions: Typing text into the box (e.g., “Playwright automation”), Adding key presses like Enter to submit the search.
7. Interact with Search Results
  • Once Google displays results, Playwright can: Locate all result links, Click on the first result or verify that certain text is present, Extract text from search results for validation.
8. Handle Dynamic Behavior
  • Google search results often load dynamically, so Playwright’s auto-waiting ensures it waits for elements to be ready before interacting.
  • For example, it won’t try to click a result before the page is fully interactive.
9. Perform Additional Actions
  • You can automate actions beyond just searching: Navigate to the Images or News tab, open links in new tabs, validate page titles or URLs to confirm successful navigation.
10. Close Browser
  • At the end of the automation, Playwright closes the browser or context to free resources.













Website to be automated: https://www.google.com









Maven Dependencies


<dependencies>
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.44.0</version> <!-- Use latest if available -->
    </dependency>
</dependencies>


Java Code to Automate Google Search


import com.microsoft.playwright.*;

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

            // Step 2: Create a new browser context and page
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Step 3: Navigate to Google
            page.navigate("https://www.google.com");

            // Step 4: Accept cookies if visible (optional step depending on location)
            Locator acceptButton = page.locator("button:has-text('I agree'), button:has-text('Accept all')");
            if (acceptButton.isVisible()) {
                acceptButton.click();
            }

            // Step 5: Type a query into the search box
            page.locator("[name='q']").fill("Playwright Java");

            // Step 6: Press Enter to search
            page.keyboard().press("Enter");

            // Step 7: Wait for results to load and print titles
            page.waitForSelector("h3");  // wait for results

            System.out.println("Top Search Results:");
            for (Locator result : page.locator("h3").all()) {
                System.out.println(result.textContent());
            }

            // Step 8: Close browser
            browser.close();
        }
    }
}


Code Explanation:


StepDescription
Playwright.create()Initializes Playwright engine.
browser.newContext()Creates a new browser context (like an incognito window).
page.navigate()Navigates to the URL.
page.locator("[name='q']")Finds the search box on Google using the name attribute.
keyboard().press("Enter")Simulates pressing Enter to submit the form.
locator("h3")Search results on Google usually appear under <h3> tags.


Suggested Posts:

1. BrowserContext in Playwright
2. Automate GET API in Playwright
3. Comma Selectors in Playwright
4. Handle Alerts in Playwright
5. Find Web Elements by XPath in Playwright

How to Automate a Login Page by Playwright Java




When automating a login page with Playwright in Java, the process involves simulating the exact steps a real user would perform when logging into a web application. Here’s the conceptual flow:

1. Test Preparation

  • Launch Browser: Use Playwright to start a browser instance (Chrome, Firefox, WebKit).
  • Create Context and Page: A browser context is like a fresh user session, and a page represents a single browser tab. These are required to isolate the login test.

2. Navigating to the Login Page
  • Direct the browser to the application’s login URL.
  • Ensure the page is fully loaded before proceeding (Playwright automatically waits for the page to be ready, but explicit waits can be used for synchronization).
3. Interacting with Input Fields
  • Locate Username Field: Identify the username/email input box using a selector (ID, name, placeholder, or CSS).
  • Locate Password Field: Similarly, find the password input field.
  • Enter Credentials: Simulate typing the username and password into their respective fields.
4. Clicking the Login Button
  • Identify the login/submit button on the page.
  • Simulate a user click on the button. Playwright ensures the element is ready for interaction before performing the click.
5. Handling Synchronization
  • After clicking login, the application might redirect to another page (like a dashboard).
  • Playwright automatically waits for navigation, but you may also wait for a specific element on the home/dashboard page to confirm successful login.
6. Validation of Login
  • Positive Scenario: Verify that a unique element on the home page (e.g., a profile icon, welcome message, or logout button) is visible, confirming login success.
  • Negative Scenario: Check for error messages (example: “Invalid username or password”) when wrong credentials are entered.
7. Security & Session Handling
  • Playwright allows capturing and storing cookies or session tokens. This can be reused in future tests to avoid repeated logins.
  • Browser Context ensures each test runs in isolation, preventing session overlap.
8. Tear Down
  • After test execution, close the page, context, and browser to free up resources.
  • This ensures test environments remain clean and consistent.












Website to be automated: 

https://opensource-demo.orangehrmlive.com/web/index.php/auth/login






Add maven dependency in pom.xml:

<dependencies>
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.44.0</version>
    </dependency>
</dependencies>

Java Code to Automate Login


import com.microsoft.playwright.*;

public class OrangeHRMLoginTest {
    public static void main(String[] args) {
        // Step 1: Launch Playwright
        try (Playwright playwright = Playwright.create()) {

            // Step 2: Launch a browser (Chromium)
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // Step 3: Create a new browser context
            BrowserContext context = browser.newContext();

            // Step 4: Open a new page
            Page page = context.newPage();

            // Step 5: Navigate to the login page
            page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

            // Step 6: Wait for username input field to be visible
            page.waitForSelector("input[name='username']");

            // Step 7: Fill in the login credentials
            page.fill("input[name='username']", "Admin");
            page.fill("input[name='password']", "admin123");

            // Step 8: Click the login button
            page.click("button[type='submit']");

            // Step 9: Print login success message
            System.out.println("Login successful!");

            // Optional: Close browser after verification
            browser.close();
        }
    }
}

Code explanation:

Line/BlockExplanation
Playwright.create()Starts Playwright engine
chromium().launch(...)Launches Chromium browser (can be firefox() or webkit() too)
browser.newContext()Creates a new isolated browser context (like incognito)
context.newPage()Opens a new browser tab/page
page.navigate(url)Opens the specified URL
page.fill(selector, value)Enters value into input field (selector is a CSS locator)
page.click(selector)Clicks the element (e.g., login button)
browser.close()Closes the browser at the end

Required Credentials

For this demo:

  • Username: Admin
  • Password: admin123


Points to Consider:
  • This script assumes that the page loads fast enough, but for real-world tests, you should use explicit waits where needed.
  • You can run this from a main method or integrate it into a test framework like JUnit/TestNG for proper test cases.

Count Multiple Elements in Dropdown in Playwright

 



Dropdown in Playwright

A dropdown is usually represented in HTML using a <select> tag with multiple <option> elements, or sometimes as a custom dropdown built with <div> or <li> elements.

When working with dropdowns in automation, sometimes you don’t just want to select an option, but also count how many options are present.


Counting Multiple Elements in a Dropdown in Playwright

(1) Locate the Dropdown

  • First, you need to identify the dropdown element (e.g., <select> or custom dropdown).
  • In Playwright, we interact with it using a Locator.


(2) Identify Dropdown Options

  • Inside the dropdown, multiple child elements represent available options. For <select>, these are <option> elements. For custom dropdowns, it could be <li>, <div>, or any repeated tag structure.

(3) Retrieve All Options

  • Using Playwright, you can fetch all the matching elements (for example, all <option> tags inside the dropdown).
  • This gives you a list/collection of elements.

(4) Count the Elements

  • Once you have the collection, you can count how many elements are present.
  • This tells you the total number of items in the dropdown.

(5) Use Cases in Testing

  • Validation: Verify the dropdown has the expected number of options.
  • Dynamic dropdowns: Check if the options are loading correctly (e.g., states list changes when you pick a country).
  • Data-driven testing: Ensure that no option is missing or duplicated.










Example Website:

We’ll use: https://rahulshettyacademy.com/AutomationPractice/






Code in Playwright Java:

import com.microsoft.playwright.*;

public class DropdownCountExample {
    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 demo site
            page.navigate("https://rahulshettyacademy.com/AutomationPractice/");

            // Locate the dropdown and get all option elements
            Locator dropdownOptions = page.locator("#dropdown-class-example");

            // Count the number of dropdown options
            int optionCount = dropdownOptions.count();
            System.out.println("Total options in dropdown: " + optionCount);

            // Print each option text
            for (int i = 0; i < optionCount; i++) {
                System.out.println("Option " + (i + 1) + ": " + dropdownOptions.nth(i).textContent());
            }

            browser.close();
        }
    }
}

Code explanation:


Code for count multiple elements: