Source code for langchain_community.tools.playwright.utils
"""Utilities for the Playwright browser tools."""from__future__importannotationsimportasynciofromtypingimportTYPE_CHECKING,Any,Coroutine,List,Optional,TypeVarifTYPE_CHECKING:fromplaywright.async_apiimportBrowserasAsyncBrowserfromplaywright.async_apiimportPageasAsyncPagefromplaywright.sync_apiimportBrowserasSyncBrowserfromplaywright.sync_apiimportPageasSyncPage
[docs]asyncdefaget_current_page(browser:AsyncBrowser)->AsyncPage:""" Asynchronously get the current page of the browser. Args: browser: The browser (AsyncBrowser) to get the current page from. Returns: AsyncPage: The current page. """ifnotbrowser.contexts:context=awaitbrowser.new_context()returnawaitcontext.new_page()context=browser.contexts[0]# Assuming you're using the default browser contextifnotcontext.pages:returnawaitcontext.new_page()# Assuming the last page in the list is the active onereturncontext.pages[-1]
[docs]defget_current_page(browser:SyncBrowser)->SyncPage:""" Get the current page of the browser. Args: browser: The browser to get the current page from. Returns: SyncPage: The current page. """ifnotbrowser.contexts:context=browser.new_context()returncontext.new_page()context=browser.contexts[0]# Assuming you're using the default browser contextifnotcontext.pages:returncontext.new_page()# Assuming the last page in the list is the active onereturncontext.pages[-1]
[docs]defcreate_async_playwright_browser(headless:bool=True,args:Optional[List[str]]=None)->AsyncBrowser:""" Create an async playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. args: arguments to pass to browser.chromium.launch Returns: AsyncBrowser: The playwright browser. """fromplaywright.async_apiimportasync_playwrightbrowser=run_async(async_playwright().start())returnrun_async(browser.chromium.launch(headless=headless,args=args))
[docs]defcreate_sync_playwright_browser(headless:bool=True,args:Optional[List[str]]=None)->SyncBrowser:""" Create a playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. args: arguments to pass to browser.chromium.launch Returns: SyncBrowser: The playwright browser. """fromplaywright.sync_apiimportsync_playwrightbrowser=sync_playwright().start()returnbrowser.chromium.launch(headless=headless,args=args)
T=TypeVar("T")
[docs]defrun_async(coro:Coroutine[Any,Any,T])->T:"""Run an async coroutine. Args: coro: The coroutine to run. Coroutine[Any, Any, T] Returns: T: The result of the coroutine. """event_loop=asyncio.get_event_loop()returnevent_loop.run_until_complete(coro)