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

如何使用Selenium获取指定元素的前序元素动态数值?

Solution to Get Preceding Sibling Element in Selenium

Hey there! Since you can already locate the element that comes right after your target value "1841", we can leverage XPath's sibling axes to grab that preceding value without relying on the overused KpiValue class. Here are a few reliable approaches:

1. Directly Grab the Immediate Preceding Sibling

The simplest way is to use XPath's preceding-sibling axis to fetch the very first element that sits right before the one you can already locate.

Code Example:

# First locate the element you already have a path for
sibling_element = b.find_element_by_xpath("//*[contains(text(), 'value_to_alert')]")

# Fetch its immediate preceding sibling
target_value_element = sibling_element.find_element_by_xpath("./preceding-sibling::*[1]")

# Extract the numerical text
target_value = target_value_element.text
print(target_value)  # Should output '1841'

You can also combine this into a single XPath query for efficiency:

target_value_element = b.find_element_by_xpath("//*[contains(text(), 'value_to_alert')]/preceding-sibling::*[1]")
target_value = target_value_element.text

2. Narrow Down with Specific Tag Name

If you know the HTML tag of your target value element (e.g., <span> or <div>), you can make the query more precise to avoid accidental matches:

# Replace 'span' with the actual tag of your target value element
target_value_element = b.find_element_by_xpath("//*[contains(text(), 'value_to_alert')]/preceding-sibling::span[1]")

If there are extra elements between your target value and the sibling you can locate, first find their shared parent element to limit the search scope, then pick the correct KpiValue element within that parent:

# Locate the common parent of both elements (adjust the tag to match your page's structure)
parent_container = b.find_element_by_xpath("//*[contains(text(), 'value_to_alert')]/parent::div")

# Now find the KpiValue element inside this parent
target_value_element = parent_container.find_element_by_xpath(".//*[@class='KpiValue']")

This works because we're restricting the search to only the parent container that holds both your target value and the sibling you can already find, avoiding all the other KpiValue elements on the page.


内容的提问来源于stack exchange,提问作者Bo Qiang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:55:00