You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium XPath获取仅含文本的兄弟节点文本内容报错求助

解决方法

错误原因

Selenium的find_element/find_elements方法仅支持定位元素节点,无法直接定位文本节点。你写的following-sibling::text()返回的是文本节点对象,不符合方法要求,因此抛出InvalidSelectorException。

可行方案

方案1:定位父元素后提取文本

直接定位包含目标文本的父元素,获取其全部文本后处理:

# 定位父li元素
parent_element = driver.find_element('xpath', '//li[@class="icon-feature"]')
# 获取元素的所有文本内容(包含子元素的文本和同级文本节点)
full_text = parent_element.get_attribute('textContent')
# 去除前后空格,得到目标内容
target_text = full_text.strip()

方案2:通过JavaScript执行XPath获取文本节点

利用Selenium的execute_script方法执行JS,直接获取文本节点的内容:

# 执行JS获取目标文本节点的内容并去除空格
target_text = driver.execute_script("""
    return document.evaluate(
        '//li[@class="icon-feature"]//i[@class="icon-stotal"]/following-sibling::text()[1]',
        document,
        null,
        XPathResult.STRING_TYPE,
        null
    ).stringValue.trim();
""")

方案3:结合XPath的normalize-space函数

通过JS执行带normalize-space的XPath,直接返回格式化后的文本:

target_text = driver.execute_script("""
    return document.evaluate(
        'normalize-space(//li[@class="icon-feature"]//i[@class="icon-stotal"]/following-sibling::text()[1])',
        document,
        null,
        XPathResult.STRING_TYPE,
        null
    ).stringValue;
""")

以上三种方法都能获取到你需要的121 m2 Total内容。

内容的提问来源于stack exchange,提问作者Freddy Andrés Cuellar López

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:01:44