获取元素的xpath和css_path属性时忽略id,避免页面上有重复id导致不准确

This commit is contained in:
g1879 2020-12-08 09:25:42 +08:00
parent 1a0d850cef
commit 84f18bbd50
2 changed files with 14 additions and 17 deletions

View File

@ -487,7 +487,7 @@ class DriverElement(DrissionElement):
"""返获取css路径或xpath路径"""
if mode == 'xpath':
txt1 = 'var tag = el.nodeName.toLowerCase();'
txt2 = '''return '//' + tag + '[@id="' + el.id + '"]' + path;'''
# txt2 = '''return '//' + tag + '[@id="' + el.id + '"]' + path;'''
txt3 = ''' && sib.nodeName.toLowerCase()==tag'''
txt4 = '''
if(nth>1){path = '/' + tag + '[' + nth + ']' + path;}
@ -495,7 +495,7 @@ class DriverElement(DrissionElement):
txt5 = '''return path;'''
elif mode == 'css':
txt1 = ''
txt2 = '''return '#' + el.id + path;'''
# txt2 = '''return '#' + el.id + path;'''
txt3 = ''
txt4 = '''path = '>' + ":nth-child(" + nth + ")" + path;'''
txt5 = '''return path.substr(1);'''
@ -508,16 +508,13 @@ class DriverElement(DrissionElement):
var path = '';
while (el.nodeType === Node.ELEMENT_NODE) {
''' + txt1 + '''
if (el.id) {
''' + txt2 + '''
} else {
var sib = el, nth = 0;
while (sib) {
if(sib.nodeType === Node.ELEMENT_NODE''' + txt3 + '''){nth += 1;}
sib = sib.previousSibling;
}
''' + txt4 + '''
}
el = el.parentNode;
}
''' + txt5 + '''

View File

@ -284,20 +284,20 @@ class SessionElement(DrissionElement):
ele = self
while ele:
ele_id = ele.attr('id')
# ele_id = ele.attr('id')
if ele_id:
return f'#{ele_id}{path_str}' if mode == 'css' else f'//{ele.tag}[@id="{ele_id}"]{path_str}'
# if ele_id:
# return f'#{ele_id}{path_str}' if mode == 'css' else f'//{ele.tag}[@id="{ele_id}"]{path_str}'
# else:
if mode == 'css':
brothers = len(ele.eles(f'xpath:./preceding-sibling::*'))
path_str = f'>:nth-child({brothers + 1}){path_str}'
else:
brothers = len(ele.eles(f'xpath:./preceding-sibling::{ele.tag}'))
path_str = f'/{ele.tag}[{brothers + 1}]{path_str}' if brothers > 0 else f'/{ele.tag}{path_str}'
if mode == 'css':
brothers = len(ele.eles(f'xpath:./preceding-sibling::*'))
path_str = f'>:nth-child({brothers + 1}){path_str}'
else:
brothers = len(ele.eles(f'xpath:./preceding-sibling::{ele.tag}'))
path_str = f'/{ele.tag}[{brothers + 1}]{path_str}' if brothers > 0 else f'/{ele.tag}{path_str}'
ele = ele.parent
ele = ele.parent
return path_str[1:] if mode == 'css' else path_str