Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch persistent context from current directory in playwright

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!


1 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')
like image 139
Charchit Agarwal Avatar answered Jun 25 '26 10:06

Charchit Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!