修复'Inspected target navigated or closed'导致的问题;修改下载功能,未完成

This commit is contained in:
g1879 2023-05-10 18:11:12 +08:00
parent 35f3aaa785
commit 594a71a549
7 changed files with 51 additions and 21 deletions

View File

@ -301,10 +301,13 @@ class ChromiumBase(BasePage):
@property
def ready_state(self):
"""返回当前页面加载状态,'loading' 'interactive' 'complete'有弹出框时返回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',

View File

@ -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:
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):
"""当接收到浏览器信息,执行已绑定的方法"""

View File

@ -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)

9
DrissionPage/common.pyi Normal file
View File

@ -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

View File

@ -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:

View File

@ -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: ...

View File

@ -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'