降低失去元素报错可能性

This commit is contained in:
g1879 2024-04-03 17:43:32 +08:00
parent 415747731c
commit 6de716159f
6 changed files with 27 additions and 7 deletions

View File

@ -125,6 +125,10 @@ class ChromiumElement(DrissionElement):
try: try:
attrs = self.owner.run_cdp('DOM.getAttributes', nodeId=self._node_id)['attributes'] attrs = self.owner.run_cdp('DOM.getAttributes', nodeId=self._node_id)['attributes']
return {attrs[i]: attrs[i + 1] for i in range(0, len(attrs), 2)} return {attrs[i]: attrs[i + 1] for i in range(0, len(attrs), 2)}
except ElementLostError:
self._refresh_id()
attrs = self.owner.run_cdp('DOM.getAttributes', nodeId=self._node_id)['attributes']
return {attrs[i]: attrs[i + 1] for i in range(0, len(attrs), 2)}
except CDPError: # 文档根元素不能调用此方法 except CDPError: # 文档根元素不能调用此方法
return {} return {}
@ -736,6 +740,11 @@ class ChromiumElement(DrissionElement):
self._tag = n['localName'] self._tag = n['localName']
return n['backendNodeId'] return n['backendNodeId']
def _refresh_id(self):
"""根据backend id刷新其它id"""
self._obj_id = self._get_obj_id(backend_id=self._backend_id)
self._node_id = self._get_node_id(obj_id=self._obj_id)
def _get_ele_path(self, mode): def _get_ele_path(self, mode):
"""返获取绝对的css路径或xpath路径""" """返获取绝对的css路径或xpath路径"""
if mode == 'xpath': if mode == 'xpath':
@ -1106,8 +1115,8 @@ class ShadowRoot(BaseElement):
r = make_chromium_eles(self.owner, _ids=node_id, is_obj_id=False) r = make_chromium_eles(self.owner, _ids=node_id, is_obj_id=False)
return None if r is False else r return None if r is False else r
else: else:
node_ids = [self.owner.run_cdp('DOM.querySelector', nodeId=self._node_id, selector=i)['nodeId'] node_ids = [self.owner.run_cdp('DOM.querySelector',
for i in css] nodeId=self._node_id, selector=i)['nodeId'] for i in css]
if 0 in node_ids: if 0 in node_ids:
return None return None
r = make_chromium_eles(self.owner, _ids=node_ids, index=index, is_obj_id=False) r = make_chromium_eles(self.owner, _ids=node_ids, index=index, is_obj_id=False)

View File

@ -243,6 +243,8 @@ class ChromiumElement(DrissionElement):
def _get_backend_id(self, node_id: int) -> int: ... def _get_backend_id(self, node_id: int) -> int: ...
def _refresh_id(self) -> None: ...
def _get_ele_path(self, mode: str) -> str: ... def _get_ele_path(self, mode: str) -> str: ...

View File

@ -10,6 +10,7 @@ from pathlib import Path
from threading import Lock from threading import Lock
from typing import Union, Tuple from typing import Union, Tuple
from ..errors import BaseError
from .._pages.chromium_base import ChromiumBase from .._pages.chromium_base import ChromiumBase
@ -45,4 +46,4 @@ def wait_until(function: callable, kwargs: dict = None, timeout: float = 10): ..
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(result: dict, ignore=None) -> None: ... def raise_error(result: dict, ignore: BaseError = None) -> None: ...

View File

@ -30,7 +30,7 @@ from .._units.scroller import PageScroller
from .._units.setter import ChromiumBaseSetter from .._units.setter import ChromiumBaseSetter
from .._units.states import PageStates from .._units.states import PageStates
from .._units.waiter import BaseWaiter from .._units.waiter import BaseWaiter
from ..errors import ContextLostError, CDPError, PageDisconnectedError, ElementNotFoundError from ..errors import ContextLostError, CDPError, PageDisconnectedError, ElementNotFoundError, ElementLostError
__ERROR__ = 'error' __ERROR__ = 'error'
@ -671,7 +671,7 @@ class ChromiumBase(BasePage):
return return
ele = self._ele(loc_or_ele, raise_err=False) ele = self._ele(loc_or_ele, raise_err=False)
if ele: if ele:
self.run_cdp('DOM.removeNode', nodeId=ele._node_id) self.run_cdp('DOM.removeNode', nodeId=ele._node_id, _ignore=ElementLostError)
def add_ele(self, html_or_info, insert_to=None, before=None): def add_ele(self, html_or_info, insert_to=None, before=None):
"""新建一个元素 """新建一个元素

View File

@ -102,7 +102,8 @@ class ElementRect(object):
:return: 四个角坐标 :return: 四个角坐标
""" """
return self._ele.owner.run_cdp('DOM.getBoxModel', backendNodeId=self._ele._backend_id, return self._ele.owner.run_cdp('DOM.getBoxModel', backendNodeId=self._ele._backend_id,
nodeId=self._ele._node_id, objectId=self._ele._obj_id)['model'][quad] # nodeId=self._ele._node_id, objectId=self._ele._obj_id
)['model'][quad]
def _get_page_coord(self, x, y): def _get_page_coord(self, x, y):
"""根据视口坐标获取绝对坐标""" """根据视口坐标获取绝对坐标"""

View File

@ -14,6 +14,7 @@ from .cookies_setter import SessionCookiesSetter, CookiesSetter, WebPageCookiesS
from .._functions.settings import Settings from .._functions.settings import Settings
from .._functions.tools import show_or_hide_browser from .._functions.tools import show_or_hide_browser
from .._functions.web import format_headers from .._functions.web import format_headers
from ..errors import ElementLostError
class BasePageSetter(object): class BasePageSetter(object):
@ -476,7 +477,13 @@ class ChromiumElementSetter(object):
:param value: 属性值 :param value: 属性值
:return: None :return: None
""" """
self._ele.owner.run_cdp('DOM.setAttributeValue', nodeId=self._ele._node_id, name=name, value=str(value)) try:
self._ele.owner.run_cdp('DOM.setAttributeValue',
nodeId=self._ele._node_id, name=name, value=str(value))
except ElementLostError:
self._ele._refresh_id()
self._ele.owner.run_cdp('DOM.setAttributeValue',
nodeId=self._ele._node_id, name=name, value=str(value))
def property(self, name, value): def property(self, name, value):
"""设置元素property属性 """设置元素property属性