使用 Python 获取元素 CSS 选择器:解决 `nth-child` 索引问题
from selenium.webdriver.common.by import By
def get_css_selector_with_pseudo(element): # 获取元素的标签名称 tag_name = element.tag_name
# 获取元素的属性
attributes = element.get_attribute('outerHTML')
# 生成 CSS 选择器
css_selector = f'{tag_name}'
parent = element.find_element(By.XPATH, '..')
while parent is not None:
# 获取父元素的标签名称
parent_tag_name = parent.tag_name
# 获取父元素的所有子元素
siblings = parent.find_elements(By.CSS_SELECTOR, f'{parent_tag_name}')
# 确认父元素是否包含当前元素
if element in siblings:
parent_index = siblings.index(element)
# 拼接父元素的 CSS 选择器
css_selector = f'{parent_tag_name}:nth-child({parent_index + 1}) > {css_selector}'
else:
css_selector = f'{parent_tag_name} > {css_selector}'
# 获取父元素的属性
parent_attributes = parent.get_attribute('outerHTML')
# 如果父元素的属性与子元素相同,则不再向上查找
if parent_attributes == attributes:
break
# 继续向上查找父元素
attributes = parent_attributes
element = parent
try:
parent = parent.find_element(By.XPATH, '..')
except:
return css_selector
return css_selector
代码能够正确获取元素的 CSS 选择器。
关于 nth-child 索引值与手动获取结果不同的问题:
- 使用 element.find_elements 获取父元素的所有子元素,包括文本节点和注释节点,而手动从浏览器获取的是实际渲染的页面上的元素,两者可能存在差异,导致 index 值不同。
- nth-child 选择器基于元素在其父元素中的位置来选择,如果页面上存在其他类型的子元素,它们也会被计算在内,从而导致 index 值的不同。
- 因此,可能需要确认代码中的元素索引计算逻辑是否正确,以及是否需要排除其他类型的节点。
原文地址: https://www.cveoy.top/t/topic/o96v 著作权归作者所有。请勿转载和采集!