DrissionElement添加xpath属性

This commit is contained in:
g1879 2020-08-11 10:16:54 +08:00
parent e0d4b37655
commit a522b472e0
3 changed files with 31 additions and 9 deletions

View File

@ -19,6 +19,7 @@ class DrissionElement(object):
def __init__(self, ele: Union[Element, WebElement]):
self._inner_ele = ele
self._xpath = None
@property
def inner_ele(self) -> Union[WebElement, Element]:
@ -54,20 +55,25 @@ class DrissionElement(object):
@property
def xpath(self):
def get_xpath(ele: DrissionElement, xpath_str=''):
self._xpath = self._xpath or self._get_xpath()
return self._xpath
def _get_xpath(self):
"""获取当前元素xpath字符串"""
xpath_str = ''
ele = self
while ele:
ele_id = ele.attr('id')
if ele_id:
return None, f'//*[@id="{ele_id}"]{xpath_str}'
return f'//{ele.tag}[@id="{ele_id}"]{xpath_str}'
else:
brothers = len(ele.eles(f'xpath:./preceding-sibling::{ele.tag}', timeout=0.001)) # FIXME: 修改这里
if 'SessionElement' in str(type(self)):
brothers = len(ele.eles(f'xpath:./preceding-sibling::{ele.tag}'))
else:
brothers = len(ele.eles(f'xpath:./preceding-sibling::{ele.tag}', timeout=0.001))
xpath_str = f'/{ele.tag}[{brothers + 1}]{xpath_str}' if brothers > 0 else f'/{ele.tag}{xpath_str}'
ele = ele.parent
print(xpath_str)
while ele:
ele, xpath_str = get_xpath(ele, xpath_str)
return ele, xpath_str
return get_xpath(self)[1]
return xpath_str
@abstractmethod
def ele(self, loc: Union[tuple, str], mode: str = None, show_errmsg: bool = True):

View File

@ -1064,6 +1064,10 @@ Parameter Description:
Returns the element label name text.
### xpath
Return the xpath path of the element.
### parent
Returns the parent element object.
@ -1311,6 +1315,10 @@ Parameter Description:
Returns the element label name text.
### xpath
Return the xpath path of the element.
### parent
Returns the parent element object.

View File

@ -1063,6 +1063,10 @@ driver模式的元素对象包装了一个WebElement对象并封装了常
返回元素标签名文本。
### xpath
返回元素xpath路径。
### parent
返回父级元素对象。
@ -1310,6 +1314,10 @@ session模式的元素对象包装了一个Element对象并封装了常用
返回元素标签名文本。
### xpath
返回元素xpath路径。
### parent
返回父级元素对象。