diff --git a/DrissionPage/_elements/session_element.py b/DrissionPage/_elements/session_element.py index d0cba7a..4a9aa86 100644 --- a/DrissionPage/_elements/session_element.py +++ b/DrissionPage/_elements/session_element.py @@ -155,11 +155,14 @@ class SessionElement(DrissionElement): if id_: path_str = f'>{ele.tag}#{id_}{path_str}' break - brothers = len(ele.eles(f'xpath:./preceding-sibling::*')) - path_str = f'>{ele.tag}:nth-child({brothers + 1}){path_str}' + before_brothers = len(ele.eles(f'xpath:./preceding-sibling::*')) + after_brothers = len(ele.eles(f'xpath:./following-sibling::*')) + path_str = f'>{ele.tag}:nth-child({before_brothers + 1}){path_str}' if ( + before_brothers or after_brothers) else f'>{ele.tag}{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}' + before_brothers = len(ele.eles(f'xpath:./preceding-sibling::{ele.tag}')) + after_brothers = len(ele.eles(f'xpath:./following-sibling::{ele.tag}')) + path_str = f'/{ele.tag}[{before_brothers + 1}]{path_str}' if before_brothers > 0 else f'/{ele.tag}[1]{path_str}' if after_brothers > 0 else f'/{ele.tag}{path_str}' ele = ele.parent()