mirror of
https://gitee.com/g1879/DrissionPage.git
synced 2024-12-10 04:00:23 +08:00
4.0.0b23优化处理alert逻辑
This commit is contained in:
parent
8e3e0750ce
commit
79c6eae2db
@ -13,4 +13,4 @@ from ._configs.chromium_options import ChromiumOptions
|
|||||||
from ._configs.session_options import SessionOptions
|
from ._configs.session_options import SessionOptions
|
||||||
|
|
||||||
__all__ = ['ChromiumPage', 'ChromiumOptions', 'SessionOptions', 'SessionPage', 'WebPage', '__version__']
|
__all__ = ['ChromiumPage', 'ChromiumOptions', 'SessionOptions', 'SessionPage', 'WebPage', '__version__']
|
||||||
__version__ = '4.0.0b22'
|
__version__ = '4.0.0b23'
|
||||||
|
@ -83,14 +83,15 @@ class Driver(object):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
except Empty:
|
except Empty:
|
||||||
if self.alert_flag:
|
# if self.alert_flag:
|
||||||
self.alert_flag = False
|
# self.alert_flag = False
|
||||||
self.method_results.pop(ws_id, None)
|
# self.method_results.pop(ws_id, None)
|
||||||
return {'result': {'message': 'alert exists.'}}
|
# return {'result': {'message': 'alert exists.'}}
|
||||||
|
|
||||||
elif timeout is not None and perf_counter() > end_time:
|
if timeout is not None and perf_counter() > end_time:
|
||||||
self.method_results.pop(ws_id, None)
|
self.method_results.pop(ws_id, None)
|
||||||
return {'error': {'message': 'timeout'}}
|
return {'error': {'message': 'alert exists.'}} \
|
||||||
|
if self.alert_flag else {'error': {'message': 'timeout'}}
|
||||||
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@ -157,7 +158,7 @@ class Driver(object):
|
|||||||
if self._stopped.is_set():
|
if self._stopped.is_set():
|
||||||
return {'error': 'tab closed', 'type': 'tab_closed'}
|
return {'error': 'tab closed', 'type': 'tab_closed'}
|
||||||
|
|
||||||
timeout = kwargs.pop('_timeout', 20)
|
timeout = kwargs.pop('_timeout', 10)
|
||||||
result = self._send({'method': _method, 'params': kwargs}, timeout=timeout)
|
result = self._send({'method': _method, 'params': kwargs}, timeout=timeout)
|
||||||
if result is None:
|
if result is None:
|
||||||
return {'error': 'tab closed', 'type': 'tab_closed'}
|
return {'error': 'tab closed', 'type': 'tab_closed'}
|
||||||
|
@ -641,7 +641,8 @@ class ChromiumElement(DrissionElement):
|
|||||||
"""
|
"""
|
||||||
self.page.scroll.to_see(self)
|
self.page.scroll.to_see(self)
|
||||||
x, y = offset_scroll(self, offset_x, offset_y)
|
x, y = offset_scroll(self, offset_x, offset_y)
|
||||||
self.page.run_cdp('Input.dispatchMouseEvent', type='mouseMoved', x=x, y=y)
|
self.page.run_cdp('Input.dispatchMouseEvent', type='mouseMoved', x=x, y=y,
|
||||||
|
_ignore=AlertExistsError, _timeout=0.3)
|
||||||
|
|
||||||
def drag(self, offset_x=0, offset_y=0, duration=.5):
|
def drag(self, offset_x=0, offset_y=0, duration=.5):
|
||||||
"""拖拽当前元素到相对位置
|
"""拖拽当前元素到相对位置
|
||||||
|
@ -3,6 +3,7 @@
|
|||||||
@Author : g1879
|
@Author : g1879
|
||||||
@Contact : g1879@qq.com
|
@Contact : g1879@qq.com
|
||||||
"""
|
"""
|
||||||
|
from ..errors import AlertExistsError
|
||||||
|
|
||||||
|
|
||||||
class Keys:
|
class Keys:
|
||||||
@ -403,7 +404,7 @@ def keyDescriptionForString(_modifiers, keyString): # noqa: C901
|
|||||||
def send_key(page, modifier, key):
|
def send_key(page, modifier, key):
|
||||||
"""发送一个字,在键盘中的字符触发按键,其它直接发送文本"""
|
"""发送一个字,在键盘中的字符触发按键,其它直接发送文本"""
|
||||||
if key not in keyDefinitions:
|
if key not in keyDefinitions:
|
||||||
page.run_cdp('Input.insertText', text=key)
|
page.run_cdp('Input.insertText', text=key, _ignore=AlertExistsError, _timeout=0.3)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
description = keyDescriptionForString(modifier, key)
|
description = keyDescriptionForString(modifier, key)
|
||||||
@ -417,7 +418,8 @@ def send_key(page, modifier, key):
|
|||||||
'autoRepeat': False,
|
'autoRepeat': False,
|
||||||
'unmodifiedText': text,
|
'unmodifiedText': text,
|
||||||
'location': description['location'],
|
'location': description['location'],
|
||||||
'isKeypad': description['location'] == 3}
|
'isKeypad': description['location'] == 3,
|
||||||
|
'_ignore': AlertExistsError, '_timeout': 0.3}
|
||||||
|
|
||||||
page.run_cdp('Input.dispatchKeyEvent', **data)
|
page.run_cdp('Input.dispatchKeyEvent', **data)
|
||||||
data['type'] = 'keyUp'
|
data['type'] = 'keyUp'
|
||||||
@ -440,7 +442,7 @@ def input_text_or_keys(page, text_or_keys):
|
|||||||
return
|
return
|
||||||
|
|
||||||
if text_or_keys.endswith(('\n', '\ue007')):
|
if text_or_keys.endswith(('\n', '\ue007')):
|
||||||
page.run_cdp('Input.insertText', text=text_or_keys[:-1])
|
page.run_cdp('Input.insertText', text=text_or_keys[:-1], _ignore=AlertExistsError, _timeout=0.3)
|
||||||
send_key(page, modifier, '\n')
|
send_key(page, modifier, '\n')
|
||||||
else:
|
else:
|
||||||
page.run_cdp('Input.insertText', text=text_or_keys)
|
page.run_cdp('Input.insertText', text=text_or_keys, _ignore=AlertExistsError, _timeout=0.3)
|
||||||
|
@ -254,35 +254,40 @@ def configs_to_here(save_name=None):
|
|||||||
om.save(save_name)
|
om.save(save_name)
|
||||||
|
|
||||||
|
|
||||||
def raise_error(r):
|
def raise_error(result, ignore=None):
|
||||||
"""抛出error对应报错
|
"""抛出error对应报错
|
||||||
:param r: 包含error的dict
|
:param result: 包含error的dict
|
||||||
|
:param ignore: 要忽略的错误
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
error = r['error']
|
error = result['error']
|
||||||
if error in ('Cannot find context with specified id', 'Inspected target navigated or closed'):
|
if error in ('Cannot find context with specified id', 'Inspected target navigated or closed'):
|
||||||
raise ContextLostError
|
r = ContextLostError()
|
||||||
elif error in ('Could not find node with given id', 'Could not find object with given id',
|
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',
|
'No node with given id found', 'Node with given id does not belong to the document',
|
||||||
'No node found for given backend id'):
|
'No node found for given backend id'):
|
||||||
raise ElementLostError
|
r = ElementLostError()
|
||||||
elif error == ('tab closed', 'No target with given id found'):
|
elif error == ('tab closed', 'No target with given id found'):
|
||||||
raise PageClosedError
|
r = PageClosedError()
|
||||||
elif error == 'timeout':
|
elif error == 'timeout':
|
||||||
return
|
r = TimeoutError(f'超时。\n错误:{result["error"]}\nmethod:{result["method"]}\nargs:{result["args"]}\n'
|
||||||
# raise TimeoutError
|
f'出现这个错误可能意味着程序有bug,请把错误信息和重现方法告知作者,谢谢。\n'
|
||||||
|
'报告网站:https://gitee.com/g1879/DrissionPage/issues')
|
||||||
elif error == 'alert exists.':
|
elif error == 'alert exists.':
|
||||||
raise AlertExistsError
|
r = AlertExistsError()
|
||||||
elif error in ('Node does not have a layout object', 'Could not compute box model.'):
|
elif error in ('Node does not have a layout object', 'Could not compute box model.'):
|
||||||
raise NoRectError
|
r = NoRectError()
|
||||||
elif error == 'Cannot navigate to invalid URL':
|
elif error == 'Cannot navigate to invalid URL':
|
||||||
raise WrongURLError(f'无效的url:{r["args"]["url"]}。也许要加上"http://"?')
|
r = WrongURLError(f'无效的url:{result["args"]["url"]}。也许要加上"http://"?')
|
||||||
elif error == 'Frame corresponds to an opaque origin and its storage key cannot be serialized':
|
elif error == 'Frame corresponds to an opaque origin and its storage key cannot be serialized':
|
||||||
raise StorageError
|
r = StorageError()
|
||||||
elif error == 'Sanitizing cookie failed':
|
elif error == 'Sanitizing cookie failed':
|
||||||
raise CookieFormatError(f'cookie格式不正确:{r["args"]}')
|
r = CookieFormatError(f'cookie格式不正确:{result["args"]}')
|
||||||
elif r['type'] == 'call_method_error':
|
elif result['type'] == 'call_method_error':
|
||||||
raise CDPError(f'\n错误:{r["error"]}\nmethod:{r["method"]}\nargs:{r["args"]}\n出现这个错误可能意味着程序有bug,'
|
r = CDPError(f'\n错误:{result["error"]}\nmethod:{result["method"]}\nargs:{result["args"]}\n出现这个错误可能意味着程序有bug,'
|
||||||
'请把错误信息和重现方法告知作者,谢谢。\n报告网站:https://gitee.com/g1879/DrissionPage/issues')
|
'请把错误信息和重现方法告知作者,谢谢。\n报告网站:https://gitee.com/g1879/DrissionPage/issues')
|
||||||
else:
|
else:
|
||||||
raise RuntimeError(r)
|
r = RuntimeError(result)
|
||||||
|
|
||||||
|
if not ignore or not isinstance(r, ignore):
|
||||||
|
raise r
|
||||||
|
@ -44,4 +44,4 @@ def stop_process_on_port(port: Union[int, str]) -> None: ...
|
|||||||
def configs_to_here(file_name: Union[Path, str] = None) -> None: ...
|
def configs_to_here(file_name: Union[Path, str] = None) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
def raise_error(r: dict) -> None: ...
|
def raise_error(result: dict, ignore=None) -> None: ...
|
||||||
|
@ -449,8 +449,9 @@ class ChromiumBase(BasePage):
|
|||||||
:param cmd_args: 参数
|
:param cmd_args: 参数
|
||||||
:return: 执行的结果
|
:return: 执行的结果
|
||||||
"""
|
"""
|
||||||
|
ignore = cmd_args.pop('_ignore', None)
|
||||||
r = self.driver.run(cmd, **cmd_args)
|
r = self.driver.run(cmd, **cmd_args)
|
||||||
return r if __ERROR__ not in r else raise_error(r)
|
return r if __ERROR__ not in r else raise_error(r, ignore)
|
||||||
|
|
||||||
def run_cdp_loaded(self, cmd, **cmd_args):
|
def run_cdp_loaded(self, cmd, **cmd_args):
|
||||||
"""执行Chrome DevTools Protocol语句,执行前等待页面加载完毕
|
"""执行Chrome DevTools Protocol语句,执行前等待页面加载完毕
|
||||||
|
@ -5,6 +5,7 @@
|
|||||||
"""
|
"""
|
||||||
from time import sleep, perf_counter
|
from time import sleep, perf_counter
|
||||||
|
|
||||||
|
from ..errors import AlertExistsError
|
||||||
from .._functions.keys import modifierBit, keyDescriptionForString, input_text_or_keys, Keys
|
from .._functions.keys import modifierBit, keyDescriptionForString, input_text_or_keys, Keys
|
||||||
from .._functions.web import location_in_viewport
|
from .._functions.web import location_in_viewport
|
||||||
|
|
||||||
@ -84,7 +85,7 @@ class Actions:
|
|||||||
self.curr_x = x
|
self.curr_x = x
|
||||||
self.curr_y = y
|
self.curr_y = y
|
||||||
self._dr.run('Input.dispatchMouseEvent', type='mouseMoved', x=self.curr_x, y=self.curr_y,
|
self._dr.run('Input.dispatchMouseEvent', type='mouseMoved', x=self.curr_x, y=self.curr_y,
|
||||||
modifiers=self.modifier)
|
modifiers=self.modifier, _ignore=AlertExistsError, _timeout=0.3)
|
||||||
ss = .02 - perf_counter() + t
|
ss = .02 - perf_counter() + t
|
||||||
if ss > 0:
|
if ss > 0:
|
||||||
sleep(ss)
|
sleep(ss)
|
||||||
@ -187,7 +188,7 @@ class Actions:
|
|||||||
if on_ele:
|
if on_ele:
|
||||||
self.move_to(on_ele, duration=0)
|
self.move_to(on_ele, duration=0)
|
||||||
self._dr.run('Input.dispatchMouseEvent', type='mousePressed', button=button, clickCount=count,
|
self._dr.run('Input.dispatchMouseEvent', type='mousePressed', button=button, clickCount=count,
|
||||||
x=self.curr_x, y=self.curr_y, modifiers=self.modifier)
|
x=self.curr_x, y=self.curr_y, modifiers=self.modifier, _ignore=AlertExistsError, _timeout=0.3)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def _release(self, button):
|
def _release(self, button):
|
||||||
@ -196,7 +197,7 @@ class Actions:
|
|||||||
:return: self
|
:return: self
|
||||||
"""
|
"""
|
||||||
self._dr.run('Input.dispatchMouseEvent', type='mouseReleased', button=button, clickCount=1,
|
self._dr.run('Input.dispatchMouseEvent', type='mouseReleased', button=button, clickCount=1,
|
||||||
x=self.curr_x, y=self.curr_y, modifiers=self.modifier)
|
x=self.curr_x, y=self.curr_y, modifiers=self.modifier, _ignore=AlertExistsError, _timeout=0.3)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def scroll(self, delta_x=0, delta_y=0, on_ele=None):
|
def scroll(self, delta_x=0, delta_y=0, on_ele=None):
|
||||||
@ -209,7 +210,7 @@ class Actions:
|
|||||||
if on_ele:
|
if on_ele:
|
||||||
self.move_to(on_ele, duration=0)
|
self.move_to(on_ele, duration=0)
|
||||||
self._dr.run('Input.dispatchMouseEvent', type='mouseWheel', x=self.curr_x, y=self.curr_y,
|
self._dr.run('Input.dispatchMouseEvent', type='mouseWheel', x=self.curr_x, y=self.curr_y,
|
||||||
deltaX=delta_x, deltaY=delta_y, modifiers=self.modifier)
|
deltaX=delta_x, deltaY=delta_y, modifiers=self.modifier, _ignore=AlertExistsError, _timeout=0.3)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def up(self, pixel):
|
def up(self, pixel):
|
||||||
@ -251,6 +252,8 @@ class Actions:
|
|||||||
return self
|
return self
|
||||||
|
|
||||||
data = self._get_key_data(key, 'keyDown')
|
data = self._get_key_data(key, 'keyDown')
|
||||||
|
data['_timeout'] = .3
|
||||||
|
data['_ignore'] = AlertExistsError
|
||||||
self.page.run_cdp('Input.dispatchKeyEvent', **data)
|
self.page.run_cdp('Input.dispatchKeyEvent', **data)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
@ -265,6 +268,8 @@ class Actions:
|
|||||||
return self
|
return self
|
||||||
|
|
||||||
data = self._get_key_data(key, 'keyUp')
|
data = self._get_key_data(key, 'keyUp')
|
||||||
|
data['_timeout'] = .3
|
||||||
|
data['_ignore'] = AlertExistsError
|
||||||
self.page.run_cdp('Input.dispatchKeyEvent', **data)
|
self.page.run_cdp('Input.dispatchKeyEvent', **data)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
@ -7,7 +7,7 @@ from time import perf_counter, sleep
|
|||||||
|
|
||||||
from .._functions.settings import Settings
|
from .._functions.settings import Settings
|
||||||
from .._functions.web import offset_scroll
|
from .._functions.web import offset_scroll
|
||||||
from ..errors import CanNotClickError, CDPError, NoRectError
|
from ..errors import CanNotClickError, CDPError, NoRectError, AlertExistsError
|
||||||
|
|
||||||
|
|
||||||
class Clicker(object):
|
class Clicker(object):
|
||||||
@ -146,11 +146,11 @@ class Clicker(object):
|
|||||||
:param count: 点击次数
|
:param count: 点击次数
|
||||||
:return: None
|
:return: None
|
||||||
"""
|
"""
|
||||||
self._ele.page.run_cdp('Input.dispatchMouseEvent', type='mousePressed',
|
self._ele.page.run_cdp('Input.dispatchMouseEvent', type='mousePressed', x=client_x,
|
||||||
x=client_x, y=client_y, button=button, clickCount=count, _timeout=0.3)
|
y=client_y, button=button, clickCount=count, _ignore=AlertExistsError, _timeout=0.3)
|
||||||
# sleep(.05)
|
# sleep(.05)
|
||||||
self._ele.page.run_cdp('Input.dispatchMouseEvent', type='mouseReleased',
|
self._ele.page.run_cdp('Input.dispatchMouseEvent', type='mouseReleased', x=client_x,
|
||||||
x=client_x, y=client_y, button=button, _timeout=0.2)
|
y=client_y, button=button, _ignore=AlertExistsError, _timeout=0.2)
|
||||||
|
|
||||||
# -------------即将废弃--------------
|
# -------------即将废弃--------------
|
||||||
|
|
||||||
|
2
setup.py
2
setup.py
@ -6,7 +6,7 @@ with open("README.md", "r", encoding='utf-8') as fh:
|
|||||||
|
|
||||||
setup(
|
setup(
|
||||||
name="DrissionPage",
|
name="DrissionPage",
|
||||||
version="4.0.0b22",
|
version="4.0.0b23",
|
||||||
author="g1879",
|
author="g1879",
|
||||||
author_email="g1879@qq.com",
|
author_email="g1879@qq.com",
|
||||||
description="Python based web automation tool. It can control the browser and send and receive data packets.",
|
description="Python based web automation tool. It can control the browser and send and receive data packets.",
|
||||||
|
Loading…
x
Reference in New Issue
Block a user