XPath技术问询:查找包含两段文本的最后一个目标div(附结构)
Got it, let's break down how to fix your XPath issue. Your goal is to target the last div on the page that contains exactly two child divs (each holding plain text with no nested elements)—and your current expression is targeting the wrong level of elements entirely.
Why Your Original XPath Isn't Working
Your current expression:
.//div[normalize-space(.) and count(div[normalize-space(.)]) = 0]
This is looking for divs that:
- Have non-empty text content themselves, AND
- Have no child divs with non-empty text.
That means it's matching the two inner text divs (<div>first part of text</div> and <div>second part of text</div>) instead of their parent div (the one you actually need).
The Correct XPath Expression
To target the parent div that holds exactly two text-only child divs, and grab the last one on the page, use this:
//div[count(div[normalize-space(.) and not(*)]) = 2][last()]
Let's break this down piece by piece:
//div: Searches the entire document for all div elements.[count(div[normalize-space(.) and not(*)]) = 2]: Filters divs to only those that have exactly 2 direct child divs where:normalize-space(.): The child div has non-empty text (ignoring extra whitespace).not(*): The child div has no nested elements (so it's just plain text content).
[last()]: Picks the final matching div from all results (since you need the last one on the page, regardless of how many exist).
Adjustments If Needed
If your target div might have extra child elements (like whitespace text nodes) but you still just care about having at least two text-only child divs, modify the count condition to:
//div[count(div[normalize-space(.) and not(*)]) >= 2][last()]
Example Match
For your sample HTML structure:
<div> <!-- Unwanted div --> <div> <!-- Target div --> <div>first part of text</div> <div>second part of text</div> </div> </div>
This XPath will correctly target the "Target div" element, and if there are multiple such divs on the page, it will select the very last one.
内容的提问来源于stack exchange,提问作者Somber

