BeautifulSoup 的页面中需要获取某个元素的 xpath 路径
python
def generate_xpath(tag, is_class=True):
"""
根据页面信息获取指定内容的xpath路径
:param tag: BeautifulSoup 的页面中需要获取xpath路径的对象
:param is_class: 是否使用class进行创建xpath
:return: xpath路径
"""
def path_generator(t):
components = []
for parent in t.parents:
if parent.name == '[document]':
break
siblings = [sib for sib in parent.find_previous_siblings(t.name)
if sib.name == t.name]
position = len(siblings) + 1
components.append(f"{t.name}[{position}]")
t = parent
components.reverse()
return '/' + '/'.join(components)
# 优先检查唯一属性
if tag.get('id'):
return f"//{tag.name}[@id='{tag['id']}']"
if is_class and tag.get('class'):
return f"//{tag.name}[contains(@class,'{tag['class'][0]}')]"
return path_generator(tag)