From f485cfc7a6f521a97d3d7e57d97dde3c96e7232f Mon Sep 17 00:00:00 2001 From: g1879 Date: Fri, 19 Jan 2024 00:48:16 +0800 Subject: [PATCH] =?UTF-8?q?4.0.3.1=E5=A2=9E=E5=8A=A0reconnect()=E6=96=B9?= =?UTF-8?q?=E6=B3=95=EF=BC=9B=E4=BC=98=E5=8C=96=E5=85=B3=E9=97=AD=E6=A0=87?= =?UTF-8?q?=E7=AD=BE=E9=A1=B5=E9=80=BB=E8=BE=91=EF=BC=9B=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?s=5Fele()=E5=90=8E=E5=AE=9A=E4=BD=8D=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DrissionPage/__init__.py | 2 +- DrissionPage/_base/browser.py | 33 ++++++++++++++++++----- DrissionPage/_base/browser.pyi | 7 +++-- DrissionPage/_elements/session_element.py | 1 + DrissionPage/_pages/chromium_base.py | 11 +++++++- DrissionPage/_pages/chromium_base.pyi | 2 ++ DrissionPage/_pages/chromium_page.py | 2 +- setup.py | 2 +- 8 files changed, 48 insertions(+), 12 deletions(-) diff --git a/DrissionPage/__init__.py b/DrissionPage/__init__.py index 91fc392..78fa124 100644 --- a/DrissionPage/__init__.py +++ b/DrissionPage/__init__.py @@ -14,4 +14,4 @@ from ._configs.chromium_options import ChromiumOptions from ._configs.session_options import SessionOptions __all__ = ['ChromiumPage', 'ChromiumOptions', 'SessionOptions', 'SessionPage', 'WebPage', '__version__'] -__version__ = '4.0.3' +__version__ = '4.0.3.1' diff --git a/DrissionPage/_base/browser.py b/DrissionPage/_base/browser.py index 7c6918b..42a132b 100644 --- a/DrissionPage/_base/browser.py +++ b/DrissionPage/_base/browser.py @@ -49,7 +49,7 @@ class Browser(object): self.id = browser_id self._frames = {} self._drivers = {} - # self._drivers = {t: Driver(t, 'page', address) for t in self.tabs} + self._all_drivers = {} self._connected = False self._process_id = None @@ -64,20 +64,24 @@ class Browser(object): self._driver.set_callback('Target.targetCreated', self._onTargetCreated) def _get_driver(self, tab_id, owner=None): - """获取对应tab id的Driver + """新建并返回指定tab id的Driver :param tab_id: 标签页id :param owner: 使用该驱动的对象 :return: Driver对象 """ - return self._drivers.pop(tab_id, Driver(tab_id, 'page', self.address, owner)) + d = self._drivers.pop(tab_id, Driver(tab_id, 'page', self.address, owner)) + self._all_drivers.setdefault(tab_id, set()).add(d) + return d def _onTargetCreated(self, **kwargs): """标签页创建时执行""" if (kwargs['targetInfo']['type'] in ('page', 'webview') and not kwargs['targetInfo']['url'].startswith('devtools://')): try: - self._drivers[kwargs['targetInfo']['targetId']] = Driver(kwargs['targetInfo']['targetId'], - 'page', self.address) + tab_id = kwargs['targetInfo']['targetId'] + d = Driver(tab_id, 'page', self.address) + self._drivers[tab_id] = d + self._all_drivers.setdefault(tab_id, set()).add(d) except WebSocketBadStatusException: pass @@ -88,7 +92,10 @@ class Browser(object): self._dl_mgr.clear_tab_info(tab_id) for key in [k for k, i in self._frames.items() if i == tab_id]: self._frames.pop(key, None) + for d in self._all_drivers.get(tab_id, tuple()): + d.stop() self._drivers.pop(tab_id, None) + self._all_drivers.pop(tab_id, None) def connect_to_page(self): """执行与page相关的逻辑""" @@ -153,7 +160,16 @@ class Browser(object): :param tab_id: 标签页id :return: None """ - self.run_cdp('Target.closeTarget', targetId=tab_id, _ignore=PageDisconnectedError) + self._onTargetDestroyed(targetId=tab_id) + self.driver.run('Target.closeTarget', targetId=tab_id) + + def stop_driver(self, driver): + """停止一个Driver + :param driver: Driver对象 + :return: None + """ + driver.stop() + self._all_drivers.get(driver.id, set()).discard(driver) def activate_tab(self, tab_id): """使标签页变为活动状态 @@ -175,10 +191,15 @@ class Browser(object): :param force: 是否立刻强制终止进程 :return: None """ + for tab in self._all_drivers.values(): + for driver in tab: + driver.stop() try: self.run_cdp('Browser.close') except PageDisconnectedError: + self.driver.stop() return + self.driver.stop() if force: ip, port = self.address.split(':') diff --git a/DrissionPage/_base/browser.pyi b/DrissionPage/_base/browser.pyi index d22aaf2..af3b2c7 100644 --- a/DrissionPage/_base/browser.pyi +++ b/DrissionPage/_base/browser.pyi @@ -5,7 +5,7 @@ @Copyright: (c) 2024 by g1879, Inc. All Rights Reserved. @License : BSD 3-Clause. """ -from typing import List, Optional, Union +from typing import List, Optional, Union, Set, Dict from .driver import BrowserDriver, Driver from .._pages.chromium_page import ChromiumPage @@ -19,7 +19,8 @@ class Browser(object): id: str = ... address: str = ... _frames: dict = ... - _drivers: dict = ... + _drivers: Dict[str, Driver] = ... + _all_drivers: Dict[str, Set[Driver]] = ... _process_id: Optional[int] = ... _dl_mgr: DownloadManager = ... _connected: bool = ... @@ -49,6 +50,8 @@ class Browser(object): def close_tab(self, tab_id: str) -> None: ... + def stop_driver(self, driver: Driver) -> None: ... + def activate_tab(self, tab_id: str) -> None: ... def get_window_bounds(self, tab_id: str = None) -> dict: ... diff --git a/DrissionPage/_elements/session_element.py b/DrissionPage/_elements/session_element.py index 7c67b63..761668c 100644 --- a/DrissionPage/_elements/session_element.py +++ b/DrissionPage/_elements/session_element.py @@ -27,6 +27,7 @@ class SessionElement(DrissionElement): """ super().__init__(page) self._inner_ele = ele + self._type = 'SessionElement' @property def inner_ele(self): diff --git a/DrissionPage/_pages/chromium_base.py b/DrissionPage/_pages/chromium_base.py index 26092eb..49d7721 100644 --- a/DrissionPage/_pages/chromium_base.py +++ b/DrissionPage/_pages/chromium_base.py @@ -827,7 +827,16 @@ class ChromiumBase(BasePage): def disconnect(self): """断开与页面的连接,不关闭页面""" if self._driver: - self.driver.stop() + self.browser.stop_driver(self._driver) + + def reconnect(self, wait=0): + """断开与页面原来的页面,重新建立连接 + :param wait: 断开后等待若干秒再连接 + :return: None + """ + self.disconnect() + sleep(wait) + self._driver = self.browser._get_driver(self._target_id, self) def handle_alert(self, accept=True, send=None, timeout=None, next_one=False): r = self._handle_alert(accept=accept, send=send, timeout=timeout, next_one=next_one) diff --git a/DrissionPage/_pages/chromium_base.pyi b/DrissionPage/_pages/chromium_base.pyi index 8b10867..8e9223f 100644 --- a/DrissionPage/_pages/chromium_base.pyi +++ b/DrissionPage/_pages/chromium_base.pyi @@ -244,6 +244,8 @@ class ChromiumBase(BasePage): def disconnect(self) -> None: ... + def reconnect(self, wait: float = 0) -> None: ... + def handle_alert(self, accept: bool = True, send: str = None, timeout: float = None, next_one: bool = False) -> Union[str, False]: ... diff --git a/DrissionPage/_pages/chromium_page.py b/DrissionPage/_pages/chromium_page.py index 64f83e1..9a01ac1 100644 --- a/DrissionPage/_pages/chromium_page.py +++ b/DrissionPage/_pages/chromium_page.py @@ -203,7 +203,7 @@ class ChromiumPage(ChromiumBase): def close(self): """关闭Page管理的标签页""" - self.browser.close_tab(self.tab_id) + self.close_tabs(self.tab_id) def close_tabs(self, tabs_or_ids=None, others=False): """关闭传入的标签页,默认关闭当前页。可传入多个 diff --git a/setup.py b/setup.py index 2a450f9..2f84c94 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,7 @@ with open("README.md", "r", encoding='utf-8') as fh: setup( name="DrissionPage", - version="4.0.3", + version="4.0.3.1", author="g1879", author_email="g1879@qq.com", description="Python based web automation tool. It can control the browser and send and receive data packets.",