|
发表于 2023-5-7 14:46:48
|
显示全部楼层
要确定子元素在父元素中的位置(类似于索引),您可以使用以下方法:
- def find_child_index(parent, target_child):
- children_list = list(parent.children)
- for index, child in enumerate(children_list):
- if child == target_child:
- return index
- return -1 # 如果子元素不在父元素中,返回 -1
复制代码
在这个函数中,我们首先将父元素的 children 属性转换为 Python 列表。然后,我们遍历该列表并使用 enumerate 获取当前子元素的索引。如果找到目标子元素,则返回其索引。如果在父元素的子元素中找不到目标子元素,返回 -1 。
例如,使用以下代码获取子元素 span 在其父元素中的位置:
- span_tag = soup.find('span')
- parent = span_tag.parent
- child_index = find_child_index(parent, span_tag)
复制代码 |
|