Skip to content

[Question]: Creating a playwright instance per thread with the async api #1619

@LeilaSchooley

Description

@LeilaSchooley

Your question

I saw this #623 (comment)
how would I adapt this example for the async api? It's required for a project.

import threading
from playwright.async_api import async_playwright
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor


class Tls(threading.local):

    def __init__(self) -> None:
        self.playwright = async_playwright().start()
        print("Create playwright instance in Thread", threading.current_thread().name)


class Worker:
    tls = Tls()

    async def run(self):
        print("Launched worker in ", threading.current_thread().name)
        browser = self.tls.playwright.chromium.launch(headless=False)
        context = browser.new_context()
        page = browser.new_page()
        page.goto("http://whatsmyuseragent.org/")
        page.screenshot(path=f"example-{threading.current_thread().name}.png")
        page.close()
        context.close()
        browser.close()
        print("Stopped worker in ", threading.current_thread().name)


if __name__ == "__main__":
    with ThreadPoolExecutor(max_workers=5) as executor:
        for _ in range(50):
            worker = Worker()
            executor.submit(worker.run)

Create playwright instance in Thread MainThread
:33: RuntimeWarning: coroutine 'Worker.run' was never awaited
executor.submit(worker.run)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
85: RuntimeWarning: coroutine 'Worker.run' was never awaited
del work_item
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
sys:1: RuntimeWarning: coroutine 'PlaywrightContextManager.start' was never awaited

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions