浏览器关闭时删除记录的id

This commit is contained in:
g1879 2023-11-07 18:04:18 +08:00
parent ed8c53d738
commit 3dfbfb957f
4 changed files with 20 additions and 4 deletions

View File

@ -35,7 +35,7 @@ class Browser(object):
self.page = page
self.address = address
self._driver = BrowserDriver(browser_id, 'browser', address)
self._driver = BrowserDriver(browser_id, 'browser', address, self)
self.id = browser_id
self._frames = {}
self._drivers = {}
@ -63,7 +63,8 @@ class Browser(object):
def _onTargetCreated(self, **kwargs):
"""标签页创建时执行"""
if kwargs['targetInfo']['type'] == 'page' and not kwargs['targetInfo']['url'].startswith('devtools://'):
self._drivers[kwargs['targetInfo']['targetId']] = ChromiumDriver(kwargs['targetInfo']['targetId'], 'page', self.address)
self._drivers[kwargs['targetInfo']['targetId']] = ChromiumDriver(kwargs['targetInfo']['targetId'], 'page',
self.address)
def _onTargetDestroyed(self, **kwargs):
"""标签页关闭时执行"""
@ -166,4 +167,5 @@ class Browser(object):
break
sleep(.2)
def _on_quit(self):
Browser.BROWSERS.pop(self.id, None)

View File

@ -58,3 +58,5 @@ class Browser(object):
def _onTargetDestroyed(self, **kwargs) -> None: ...
def quit(self) -> None: ...
def _on_quit(self) -> None: ...

View File

@ -211,17 +211,18 @@ class ChromiumDriver(object):
class BrowserDriver(ChromiumDriver):
BROWSERS = {}
def __new__(cls, tab_id, tab_type, address):
def __new__(cls, tab_id, tab_type, address, browser):
if tab_id in cls.BROWSERS:
return cls.BROWSERS[tab_id]
return object.__new__(cls)
def __init__(self, tab_id, tab_type, address):
def __init__(self, tab_id, tab_type, address, browser):
if hasattr(self, '_created'):
return
self._created = True
BrowserDriver.BROWSERS[tab_id] = self
super().__init__(tab_id, tab_type, address)
self.browser = browser
def __repr__(self):
return f"<BrowserDriver {self.id}>"
@ -230,3 +231,7 @@ class BrowserDriver(ChromiumDriver):
r = get(url, headers={'Connection': 'close'})
r.close()
return r
def stop(self):
super().stop()
self.browser._on_quit()

View File

@ -10,6 +10,8 @@ from typing import Union, Callable, Dict, Optional
from requests import Response
from websocket import WebSocket
from .browser import Browser
class GenericAttr(object):
def __init__(self, name: str, tab: ChromiumDriver): ...
@ -58,5 +60,10 @@ class ChromiumDriver(object):
class BrowserDriver(ChromiumDriver):
BROWSERS: Dict[str, ChromiumDriver] = ...
browser: Browser = ...
def __new__(cls, tab_id: str, tab_type: str, address: str, browser: Browser): ...
def __init__(self, tab_id: str, tab_type: str, address: str, browser: Browser): ...
def get(self, url) -> Response: ...