How to use playwright method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

playwright_remote_context_manager.py

Source: playwright_remote_context_manager.py Github

copy
1import asyncio
2from typing import Any
3
4from greenlet import greenlet
5
6from playwright._impl._api_types import Error
7from playwright._impl._connection import Connection
8from playwright._impl._object_factory import create_remote_object
9from playwright._impl._playwright import Playwright
10from playwright._impl._transport import WebSocketTransport
11from playwright.sync_api._generated import Playwright as SyncPlaywright
12
13
14class SyncPlaywrightRemoteContextManager:
15    def __init__(self, ws_endpoint) -> None:
16        self._playwright: SyncPlaywright
17        self._ws_endpoint = ws_endpoint
18
19    def __enter__(self) -> SyncPlaywright:
20        loop: asyncio.AbstractEventLoop
21        own_loop = None
22        try:
23            loop = asyncio.get_running_loop()
24        except RuntimeError:
25            loop = asyncio.new_event_loop()
26            own_loop = loop
27        if loop.is_running():
28            raise Error(
29                """It looks like you are using Playwright Sync API inside the asyncio loop.
30Please use the Async API instead."""
31            )
32
33        def greenlet_main() -> None:
34            loop.run_until_complete(self._connection.run_as_sync())
35
36            if own_loop:
37                loop.run_until_complete(loop.shutdown_asyncgens())
38                loop.close()
39
40        dispatcher_fiber = greenlet(greenlet_main)
41        self._connection = Connection(
42            dispatcher_fiber,
43            create_remote_object,
44            WebSocketTransport(loop, self._ws_endpoint)
45        )
46
47        g_self = greenlet.getcurrent()
48
49        def callback_wrapper(playwright_impl: Playwright) -> None:
50            self._playwright = SyncPlaywright(playwright_impl)
51            g_self.switch()
52
53        self._connection.call_on_object_with_known_name(
54            "Playwright", callback_wrapper)
55
56        dispatcher_fiber.switch()
57        playwright = self._playwright
58        playwright.stop = self.__exit__  # type: ignore
59        return playwright
60
61    def start(self) -> SyncPlaywright:
62        return self.__enter__()
63
64    def __exit__(self, *args: Any) -> None:
65        self._connection.stop_sync()
66
67
68def sync_playwright_remote(ws_endpoint) -> SyncPlaywrightRemoteContextManager:
69    return SyncPlaywrightRemoteContextManager(ws_endpoint)
70
Full Screen

sync_playwright_remote.py

Source: sync_playwright_remote.py Github

copy
1import asyncio
2import importlib.metadata
3from typing import Any
4
5from greenlet import greenlet
6
7from playwright._impl._api_types import Error
8from playwright._impl._connection import Connection
9from playwright._impl._object_factory import create_remote_object
10from playwright._impl._playwright import Playwright
11from playwright._impl._transport import WebSocketTransport
12from playwright.sync_api._generated import Playwright as SyncPlaywright
13
14
15class SyncPlaywrightRemoteContextManager:
16    def __init__(self, ws_endpoint: str) -> None:
17        self._playwright: SyncPlaywright
18        self._ws_endpoint = ws_endpoint
19
20    def _make_connection(self, dispatcher_fiber, object_factory, transport, loop) -> Connection:
21        if importlib.metadata.version('playwright') < '1.15.0':
22            return Connection(
23                dispatcher_fiber,
24                create_remote_object,
25                transport)
26        else:
27            return Connection(
28                dispatcher_fiber,
29                create_remote_object,
30                transport,
31                loop)
32
33    def __enter__(self) -> SyncPlaywright:
34        loop: asyncio.AbstractEventLoop
35        own_loop = None
36        try:
37            loop = asyncio.get_running_loop()
38        except RuntimeError:
39            loop = asyncio.new_event_loop()
40            own_loop = loop
41        if loop.is_running():
42            raise Error(
43                """It looks like you are using Playwright Sync API inside the asyncio loop.
44Please use the Async API instead."""
45            )
46
47        def greenlet_main() -> None:
48            loop.run_until_complete(self._connection.run_as_sync())
49
50            if own_loop:
51                loop.run_until_complete(loop.shutdown_asyncgens())
52                loop.close()
53
54        dispatcher_fiber = greenlet(greenlet_main)
55        self._connection = self._make_connection(
56            dispatcher_fiber,
57            create_remote_object,
58            WebSocketTransport(loop, self._ws_endpoint),
59            loop)
60
61        g_self = greenlet.getcurrent()
62
63        def callback_wrapper(playwright_impl: Playwright) -> None:
64            self._playwright = SyncPlaywright(playwright_impl)
65            g_self.switch()
66
67        self._connection.call_on_object_with_known_name(
68            "Playwright", callback_wrapper)
69
70        dispatcher_fiber.switch()
71        playwright = self._playwright
72        playwright.stop = self.__exit__  # type: ignore
73        return playwright
74
75    def start(self) -> SyncPlaywright:
76        return self.__enter__()
77
78    def __exit__(self, *args: Any) -> None:
79        self._connection.stop_sync()
80
81
82def sync_playwright_remote(ws_endpoint: str) -> SyncPlaywrightRemoteContextManager:
83    return SyncPlaywrightRemoteContextManager(ws_endpoint)
84
Full Screen

remote_context_manager.py

Source: remote_context_manager.py Github

copy
1import asyncio
2
3from greenlet import greenlet
4
5from playwright._impl._api_types import Error
6from playwright._impl._connection import Connection
7from playwright._impl._object_factory import create_remote_object
8from playwright._impl._playwright import Playwright
9from playwright.sync_api._generated import Playwright as SyncPlaywright
10from playwright._impl._transport import WebSocketTransport
11
12from playwright.sync_api._context_manager import PlaywrightContextManager
13
14class PlaywrightRemoteContextManager(PlaywrightContextManager):
15    def __enter__(self) -> SyncPlaywright:
16        loop: asyncio.AbstractEventLoop
17        own_loop = None
18        try:
19            loop = asyncio.get_running_loop()
20        except RuntimeError:
21            loop = asyncio.new_event_loop()
22            own_loop = loop
23        if loop.is_running():
24            raise Error(
25                """It looks like you are using Playwright Sync API inside the asyncio loop.
26Please use the Async API instead."""
27            )
28
29        def greenlet_main() -> None:
30            loop.run_until_complete(self._connection.run_as_sync())
31
32            if own_loop:
33                loop.run_until_complete(loop.shutdown_asyncgens())
34                loop.close()
35
36        dispatcher_fiber = greenlet(greenlet_main)
37        self._connection = Connection(
38            dispatcher_fiber,
39            create_remote_object,
40            WebSocketTransport(loop, self.ws_endpoint),
41            loop,
42        )
43
44        g_self = greenlet.getcurrent()
45
46        def callback_wrapper(playwright_impl: Playwright) -> None:
47            self._playwright = SyncPlaywright(playwright_impl)
48            g_self.switch()
49
50        self._connection.call_on_object_with_known_name("Playwright", callback_wrapper)
51
52        dispatcher_fiber.switch()
53        playwright = self._playwright
54        playwright.stop = self.__exit__  # type: ignore
55        return playwright
56
57def sync_playwright_remote(ws_endpoint) -> PlaywrightRemoteContextManager:
58    m = PlaywrightRemoteContextManager()
59    m.ws_endpoint = ws_endpoint
60    return m
61
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)