如何使用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]")
3. Use Parent Element to Scope the Search
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

