Developer Snippet Diary

Playwright Tutorial , installation > Record tests, Run Tests

Playwright enables reliable end-to-end testing for modern web apps.

1. Installation:

pip install pytest-playwright

Browsers: https://playwright.dev/python/docs/browsers
playwright install #INSTALL default browsers
playwright install --help
Custom browsers: chromium, chromium-headless-shell, chromium-tip-of-tree-headless-shell, chrome, chrome-beta, msedge, msedge-beta, msedge-dev, bidi-chromium, firefox, webkit.
playwright install --with-deps chrome

playwright install # install browsers

2.RECORD TESTS

Run the below command in cmd and do some actions with opened url , Auto code will be generated you can copy that code for use

playwright codegen https://wellguider.com 

3.Tests Run

Create any file with name test_ ie test_example.py  Also need to do this with functions ie test_has_title

def test_has_title():
    with sync_playwright() as p:
        browser = p.firefox.launch(headless=False)  # Set headless=False
        page = browser.new_page()
        page.goto("https://playwright.dev/")
        browser.close()

In current working directory type pytest to runn all tests inside all files, 

pytest # run all files, all test functions auto
pytest test_login.py # only test_login.py
pytest -k test_add_a_todo_item # specific file and function

4.

open sepecific profile:

from playwright.sync_api import sync_playwright
import os

class Init:
    def __init__(self):
        self.playwright = sync_playwright().start()
        self.browser = None
        self.page = None

    def open_profile(self, profile=1, headless=False, chrome_path=None, user_data_dir=None):
        try:
            # Default Chrome path for different OS
            if not chrome_path:
                chrome_path = (
                    'C:/Program Files/Google/Chrome/Application/chrome.exe'
                    if os.name == 'nt' else
                    '/usr/bin/google-chrome'  # Example for Linux
                )

            # Use a fixed user data directory to persist history and cookies
            if not user_data_dir:
                # Set a fixed directory in the user's home directory
                user_data_dir = os.path.join(os.path.expanduser("~"), "playwright_chrome_profile")
            
            # Ensure the directory exists
            os.makedirs(user_data_dir, exist_ok=True)
            
            profile_name = f'Profile {profile}'

            # Launch browser with persistent context to maintain history and cookies
            self.browser = self.playwright.chromium.launch_persistent_context(
                user_data_dir=user_data_dir,
                executable_path=chrome_path if os.path.exists(chrome_path) else None,
                headless=headless,
                args=[
                    '--no-sandbox',  # Be cautious with this
                    '--test-type',
                    '--disable-extensions',
                    '--start-maximized',
                    '--disable-dev-shm-usage',
                    f'--profile-directory={profile_name}'
                ]
            )
            self.page = self.browser.pages[0] if self.browser.pages else self.browser.new_page()

            self.page.set_viewport_size({"width": 1280, "height": 800})
            return self.page
        except Exception as e:
            print(f"Error opening browser: {e}")
            raise

    def close(self):
        if self.browser:
            self.browser.close()
        if self.playwright:
            self.playwright.stop()

# Example usage
if __name__ == "__main__":
    init = Init()
    try:
        page = init.open_profile(profile=1, headless=False)
        page.goto("https://maps.app.goo.gl/CA7AwydAzZQ9rMi19")
        print(page.title())
        input("Press Enter to close the browser...")
    finally:
        init.close()

all chrome flags here:
https://peter.sh/experiments/chromium-command-line-switches/

Posted by: R GONDAL
Email: rizikmw@gmail.com