如何用XPath精准定位含data-coin属性的嵌套HTML元素?
Hey Brett, let's work through this XPath challenge together—since your element positions shift daily, we'll focus on building a resilient selector that doesn't rely on fragile index-based matches like :nth-child.
First, let's translate your working CSS selector into a reliable XPath, then refine it to handle layout changes:
1. Exact 1:1 XPath Mapping of Your CSS
If you want a direct translation of your existing CSS (note: this still uses position indexes which might break if elements move), here's the equivalent:
/html/body/div[contains(@class, 'page-content')]/div[contains(@class, 'container')]/div[contains(@class, 'myaccount')]/div/div[4]/ul/*[@data-coin='BTC']/div/div[2]
2. Resilient XPath (No Position Indexes)
Since daily layout changes make index selectors risky, we'll prioritize stable attributes and class names. This XPath targets your price div.col-sm-2 while ensuring it's nested under your account section and the BTC-specific element:
//div[contains(@class, 'myaccount')]//*[@data-coin='BTC']/div/div[contains(concat(' ', @class, ' '), ' col-sm-2 ')]
Why this works better:
- It avoids
div:nth-child(4)ordiv:nth-child(2)—so even if elements are added/removed around the target, it will still find the right element as long as:- The parent section has the
myaccountclass - The coin-specific element has
data-coin="BTC" - The price element has the
col-sm-2class
- The parent section has the
- The
concat(' ', @class, ' ')trick ensures we match the exact class (preventing partial matches, like if another class starts withcol-sm-2).
3. Extra Precise Version (Adds Upper Context)
If you want to eliminate any chance of accidental matches elsewhere on the page, add the upper layer classes for more context:
//div[contains(@class, 'page-content')]/div[contains(@class, 'container')]/div[contains(@class, 'myaccount')]//*[@data-coin='BTC']/div/div[contains(concat(' ', @class, ' '), ' col-sm-2 ')]
This gives you the same precision as your CSS selector, but with far better resilience to daily layout shifts.
内容的提问来源于stack exchange,提问作者Brett

