Launch persistent context from current directory in playwright

Question:

I’m using this code I found on this page to save browser context after running the code:

user_dir = '/tmp/playwright'

with sync_playwright() as p:
  browser = p.chromium.launch_persistent_context(user_dir, headless=False)
  page = browser.new_page()

But when I try to change the directory from the /tmp/playwright folder, which is created in C:, to the current folder where I’m running the code (user_dir = './tmp/playwright'), the two folders are created but the playwright folder has nothing inside!
Does anyone know how to solve it? Thanks in advance!

Asked By: BoTop

||

Answers:

Playwright does not play well with relative paths, use os.getcwd() instead. Also, note that you don’t need to ensure that directories exist, playwright creates them automatically if they don’t.

from playwright.sync_api import sync_playwright
import os

user_dir = 'tmp/playwright'
user_dir = os.path.join(os.getcwd(), user_dir)

with sync_playwright() as p:
    browser = p.chromium.launch_persistent_context(user_dir, headless=False)
    page = browser.new_page()
    page.goto('https://playwright.dev/python', wait_until='domcontentloaded')
Answered By: Charchit

You have to use Python’s path library to prevent errors!

Example:

user_dir = 'tmp/playwright'
user_dir = os.path.join(os.getcwd(), user_dir)
Answered By: Py Ton