求助:如何基于锚文本生成定位指定按钮的稳健XPath?
Got it, let's sort out this XPath issue for your button. The problem with your original expression is that you're targeting a <div> element, but your actual target is an <a> tag—no wonder it can't find the element!
Here are several robust XPath options that avoid brittle absolute paths, ranked by reliability:
Option 1: Match the exact text (with whitespace handling)
This targets the<a>tag directly and accounts for any accidental leading/trailing spaces in the text://a[normalize-space(text())='Submitted Applications']Option 2: Combine text with the
accesskeyattribute (most robust)
Sinceaccesskey="n"is a unique identifier unlikely to change with layout tweaks, pairing it with the text creates a super reliable selector://a[@accesskey='n' and normalize-space(text())='Submitted Applications']Option 3: Combine text with partial
hrefmatch
If theaccesskeymight change, use the unique part of thehrefvalue instead. Note: I noticed a typo in yourhref(webApplcationinstead ofwebApplication), but usingcontainsavoids issues with typos or minor path changes://a[contains(@href,'submittedApps') and normalize-space(text())='Submitted Applications']Bonus: Add a stable parent context (if available)
If you know the button lives inside a stable container (like a nav bar with a fixed class/id), wrap the selector in that context to narrow down matches further://div[@class='main-nav']//a[normalize-space(text())='Submitted Applications']
(Replace@class='main-nav'with your actual stable parent attribute.)
Why your original XPath failed
Your expression //div[contains(normalize-space(),'Submitted Applications')] was looking for a <div> that contains the text, but the text lives directly inside an <a> tag—so the div (if it exists) might not have that text as its own content, or you're targeting the wrong element entirely.
内容的提问来源于stack exchange,提问作者AlpineF30

