继续改进相对定位

This commit is contained in:
g1879 2021-12-21 22:29:51 +08:00
parent 38ed85edb8
commit 12fbe15761

View File

@ -173,30 +173,34 @@ class DrissionElement(BaseElement):
def _get_brothers(self,
index: int = None,
filter_loc: Union[tuple, str] = '',
direction: str = 'following') -> List['DrissionElement']:
"""按要求返回兄弟元素或节点组成的列表 \n
direction: str = 'following',
brother: bool = True,
timeout: float = .5) -> List['DrissionElement']:
"""按要求返回兄弟元素或节点组成的列表 \n
:param index: 获取第几个
:param filter_loc: 用于筛选元素的查询语法
:param direction: 'following' 'preceding'查找的方向
:param brother: 查找范围在同级查找还是整个dom前后查找
:param timeout: 查找等待时间
:return: DriverElement对象或字符串
"""
if index is not None and index < 1:
raise ValueError('index必须大于等于1。')
timeout = 0 if direction == 'preceding' else .5
brother = '-sibling' if brother else ''
# 仅根据位置取一个
if index and not filter_loc:
xpath = f'xpath:./{direction}-sibling::*[{index}]'
xpath = f'xpath:./{direction}{brother}::*[{index}]'
# 根据筛选获取所有
else:
loc = get_loc(filter_loc, True)
loc = get_loc(filter_loc, True) # 把定位符转换为xpath
if loc[0] == 'css selector':
raise ValueError('此css selector语法不受支持请换成xpath。')
loc = loc[1].lstrip('./')
xpath = f'xpath:./{direction}-sibling::{loc}'
xpath = f'xpath:./{direction}{brother}::{loc}'
nodes = self._ele(xpath, timeout=timeout, single=False)
nodes = [e for e in nodes if not (isinstance(e, str) and sub('[ \n\t\r]', '', e) == '')]