From 594a71a549983a8748d6d207853b17e9c8445ef0 Mon Sep 17 00:00:00 2001 From: g1879 Date: Wed, 10 May 2023 18:11:12 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D'Inspected=20target=20navigat?= =?UTF-8?q?ed=20or=20closed'=E5=AF=BC=E8=87=B4=E7=9A=84=E9=97=AE=E9=A2=98?= =?UTF-8?q?=EF=BC=9B=E4=BF=AE=E6=94=B9=E4=B8=8B=E8=BD=BD=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=EF=BC=8C=E6=9C=AA=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DrissionPage/chromium_base.py | 13 ++++++++----- DrissionPage/chromium_driver.py | 30 +++++++++++++++++++++--------- DrissionPage/chromium_page.py | 10 +++++----- DrissionPage/common.pyi | 9 +++++++++ DrissionPage/session_page.py | 5 +++++ DrissionPage/session_page.pyi | 1 + DrissionPage/web_page.py | 4 ++-- 7 files changed, 51 insertions(+), 21 deletions(-) create mode 100644 DrissionPage/common.pyi diff --git a/DrissionPage/chromium_base.py b/DrissionPage/chromium_base.py index 88154be..5969344 100644 --- a/DrissionPage/chromium_base.py +++ b/DrissionPage/chromium_base.py @@ -301,10 +301,13 @@ class ChromiumBase(BasePage): @property def ready_state(self): """返回当前页面加载状态,'loading' 'interactive' 'complete',有弹出框时返回None""" - try: - return self.run_cdp('Runtime.evaluate', expression='document.readyState;')['result']['value'] - except (AlertExistsError, TypeError): - return None + while True: + try: + return self.run_cdp('Runtime.evaluate', expression='document.readyState;')['result']['value'] + except (AlertExistsError, TypeError): + return None + except ContextLossError: + continue @property def size(self): @@ -382,7 +385,7 @@ class ChromiumBase(BasePage): return r error = r[ERROR] - if error == 'Cannot find context with specified id': + if error in ('Cannot find context with specified id', 'Inspected target navigated or closed'): raise ContextLossError elif error in ('Could not find node with given id', 'Could not find object with given id', 'No node with given id found', 'Node with given id does not belong to the document', diff --git a/DrissionPage/chromium_driver.py b/DrissionPage/chromium_driver.py index fbe08e1..6e1db71 100644 --- a/DrissionPage/chromium_driver.py +++ b/DrissionPage/chromium_driver.py @@ -79,7 +79,13 @@ class ChromiumDriver(object): message_json = dumps(message) if self.debug: - print(f"发> {message_json}") + if isinstance(self.debug, str) and message.get('method', '').startswith(self.debug): + print(f'发> {message_json}') + elif isinstance(self.debug, (list, tuple, set)): + for m in self.debug: + if message.get('method', '').startswith(m): + print(f'发> {message_json}') + break if not isinstance(timeout, (int, float)) or timeout > 1: q_timeout = 1 @@ -117,7 +123,7 @@ class ChromiumDriver(object): try: self._ws.settimeout(1) message_json = self._ws.recv() - message = loads(message_json) + mes = loads(message_json) except WebSocketTimeoutException: continue except (WebSocketException, OSError, WebSocketConnectionClosedException): @@ -125,17 +131,23 @@ class ChromiumDriver(object): return if self.debug: - print(f'<收 {message_json}') + if 'id' in mes or (isinstance(self.debug, str) and mes.get('method', '').startswith(self.debug)): + print(f'<收 {message_json}') + elif isinstance(self.debug, (list, tuple, set)): + for m in self.debug: + if mes.get('method', '').startswith(m): + print(f'<收 {message_json}') + break - if "method" in message: - self.event_queue.put(message) + if "method" in mes: + self.event_queue.put(mes) - elif "id" in message: - if message["id"] in self.method_results: - self.method_results[message['id']].put(message) + elif "id" in mes: + if mes["id"] in self.method_results: + self.method_results[mes['id']].put(mes) elif self.debug: - print(f'未知信息:{message}') + print(f'未知信息:{mes}') def _handle_event_loop(self): """当接收到浏览器信息,执行已绑定的方法""" diff --git a/DrissionPage/chromium_page.py b/DrissionPage/chromium_page.py index 16d7a7b..15c5dac 100644 --- a/DrissionPage/chromium_page.py +++ b/DrissionPage/chromium_page.py @@ -510,22 +510,22 @@ class ChromiumDownloadSetter(DownloadSetter): path = str(path) self._page._download_path = path try: - self._page.browser_driver.Browser.setDownloadBehavior(behavior='allow', downloadPath=path, + self._page.browser_driver.Browser.setDownloadBehavior(behavior='allowAndName', downloadPath=path, eventsEnabled=True) except CallMethodError: warn('\n您的浏览器版本太低,用新标签页下载文件可能崩溃,建议升级。') - self._page.run_cdp('Page.setDownloadBehavior', behavior='allow', downloadPath=path) + self._page.run_cdp('Page.setDownloadBehavior', behavior='allowAndName', downloadPath=path) self.DownloadKit.goal_path = path def by_browser(self): """设置使用浏览器下载文件""" try: - self._page.browser_driver.Browser.setDownloadBehavior(behavior='allow', eventsEnabled=True, + self._page.browser_driver.Browser.setDownloadBehavior(behavior='allowAndName', eventsEnabled=True, downloadPath=self._page.download_path) self._page.browser_driver.Browser.downloadWillBegin = self._download_by_browser except CallMethodError: - self._page.driver.Page.setDownloadBehavior(behavior='allow', downloadPath=self._page.download_path) + self._page.driver.Page.setDownloadBehavior(behavior='allowAndName', downloadPath=self._page.download_path) self._page.driver.Page.downloadWillBegin = self._download_by_browser self._behavior = 'allow' @@ -567,7 +567,7 @@ class ChromiumDownloadSetter(DownloadSetter): """拦截浏览器下载并用downloadKit下载""" url = kwargs['url'] if url.startswith('blob:'): - self._page.browser_driver.Browser.setDownloadBehavior(behavior='allow', eventsEnabled=True, + self._page.browser_driver.Browser.setDownloadBehavior(behavior='allowAndName', eventsEnabled=True, downloadPath=self._page.download_path) sleep(2) self._page.browser_driver.Browser.setDownloadBehavior(behavior='deny', eventsEnabled=True) diff --git a/DrissionPage/common.pyi b/DrissionPage/common.pyi new file mode 100644 index 0000000..891fe22 --- /dev/null +++ b/DrissionPage/common.pyi @@ -0,0 +1,9 @@ +# -*- coding:utf-8 -*- +from FlowViewer import Listener, RequestMan + +from .session_element import make_session_ele + +from .action_chains import ActionChains +from .commons.keys import Keys +from .commons.by import By +from .commons.constants import Settings diff --git a/DrissionPage/session_page.py b/DrissionPage/session_page.py index 3d934b9..276b093 100644 --- a/DrissionPage/session_page.py +++ b/DrissionPage/session_page.py @@ -446,6 +446,7 @@ class DownloadSetter(object): def __init__(self, page): self._page = page self._DownloadKit = None + self._file_exists = 'rename' @property def DownloadKit(self): @@ -488,18 +489,22 @@ class FileExists(object): if mode not in ('skip', 'rename', 'overwrite'): raise ValueError("mode参数只能是'skip', 'rename', 'overwrite'") self._setter.DownloadKit.file_exists = mode + self._setter._file_exists = mode def skip(self): """设为跳过""" self._setter.DownloadKit.file_exists = 'skip' + self._setter._file_exists = 'skip' def rename(self): """设为重命名,文件名后加序号""" self._setter.DownloadKit._file_exists = 'rename' + self._setter._file_exists = 'rename' def overwrite(self): """设为覆盖""" self._setter.DownloadKit._file_exists = 'overwrite' + self._setter._file_exists = 'overwrite' def check_headers(kwargs, headers, arg) -> bool: diff --git a/DrissionPage/session_page.pyi b/DrissionPage/session_page.pyi index c551834..7f535a0 100644 --- a/DrissionPage/session_page.pyi +++ b/DrissionPage/session_page.pyi @@ -205,6 +205,7 @@ class DownloadSetter(object): def __init__(self, page: Union[SessionPage, WebPage, ChromiumPage]): self._page: SessionPage = ... self._DownloadKit: DownloadKit = ... + self._file_exists: str = ... @property def DownloadKit(self) -> DownloadKit: ... diff --git a/DrissionPage/web_page.py b/DrissionPage/web_page.py index 62e1a1b..7bdeb87 100644 --- a/DrissionPage/web_page.py +++ b/DrissionPage/web_page.py @@ -535,13 +535,13 @@ class WebPageDownloadSetter(ChromiumDownloadSetter): raise RuntimeError('浏览器未连接。') try: - self._page.browser_driver.Browser.setDownloadBehavior(behavior='allow', eventsEnabled=True, + self._page.browser_driver.Browser.setDownloadBehavior(behavior='allowAndName', eventsEnabled=True, downloadPath=self._page.download_path) self._page.browser_driver.Browser.downloadWillBegin = self._download_by_browser except CallMethodError: warn('\n您的浏览器版本太低,用新标签页下载文件可能崩溃,建议升级。') - self._page.driver.Page.setDownloadBehavior(behavior='allow', downloadPath=self._page.download_path) + self._page.driver.Page.setDownloadBehavior(behavior='allowAndName', downloadPath=self._page.download_path) self._page.driver.Page.downloadWillBegin = self._download_by_browser self._behavior = 'allow'