2022-09-08 01:08:37 +00:00
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
from playwright.async_api import Browser, Playwright, async_playwright
|
|
|
|
|
|
|
|
from core.service import Service
|
|
|
|
from utils.log import logger
|
|
|
|
|
|
|
|
|
|
|
|
class AioBrowser(Service):
|
|
|
|
|
|
|
|
def __init__(self, loop=None):
|
|
|
|
self.browser: Optional[Browser] = None
|
|
|
|
self._playwright: Optional[Playwright] = None
|
|
|
|
self._loop = loop
|
|
|
|
|
|
|
|
async def start(self):
|
|
|
|
if self._playwright is None:
|
2022-09-08 04:57:22 +00:00
|
|
|
logger.info("正在尝试启动 [blue]Playwright[/]", extra={'markup': True})
|
2022-09-08 01:08:37 +00:00
|
|
|
self._playwright = await async_playwright().start()
|
2022-09-08 04:57:22 +00:00
|
|
|
logger.success("[blue]Playwright[/] 启动成功", extra={'markup': True})
|
2022-09-08 01:08:37 +00:00
|
|
|
if self.browser is None:
|
2022-09-08 04:57:22 +00:00
|
|
|
logger.info("正在尝试启动 [blue]Browser[/]", extra={'markup': True})
|
2022-09-08 01:08:37 +00:00
|
|
|
try:
|
|
|
|
self.browser = await self._playwright.chromium.launch(timeout=5000)
|
2022-09-08 04:57:22 +00:00
|
|
|
logger.success("[blue]Browser[/] 启动成功", extra={'markup': True})
|
2022-09-08 01:08:37 +00:00
|
|
|
except TimeoutError as err:
|
2022-09-08 04:57:22 +00:00
|
|
|
logger.warning("[blue]Browser[/] 启动失败", extra={'markup': True})
|
2022-09-08 01:08:37 +00:00
|
|
|
raise err
|
|
|
|
|
|
|
|
return self.browser
|
|
|
|
|
|
|
|
async def stop(self):
|
|
|
|
if self.browser is not None:
|
|
|
|
await self.browser.close()
|
|
|
|
if self._playwright is not None:
|
|
|
|
await self._playwright.stop()
|
|
|
|
|
|
|
|
async def get_browser(self) -> Browser:
|
|
|
|
if self.browser is None:
|
|
|
|
await self.start()
|
|
|
|
return self.browser
|