求助:基于多节点多条件查找表格中指定按钮的XPath
No worries, let's break down how to craft an XPath that reliably finds the "Clasament" button tied to "Spania"—the key is to link the two elements through their HTML structure. Here are the most common scenarios and corresponding XPaths:
1. "Spania" is an ancestor/parent element of the button
If your HTML looks something like this (where "Spania" lives in a container that wraps the button):
<div class="country-group"> <h2>Spania</h2> <div class="actions"> <button>Clasament</button> </div> </div>
Use this XPath to first locate the "Spania" container, then grab its descendant "Clasament" button:
//*[contains(text(), 'Spania')]/descendant::button[text()='Clasament']
//*[contains(text(), 'Spania')]finds any element containing the text "Spania" (usetext()='Spania'for exact matches if there's no extra whitespace)/descendant::button[text()='Clasament']drills down to the button with the exact text "Clasament" inside that container
2. "Spania" and the button share the same parent
If they're in a row or adjacent cells like this:
<tr> <td>Spania</td> <td><button>Clasament</button></td> </tr>
Target the "Spania" cell, then jump to its sibling cell holding the button:
//td[text()='Spania']/following-sibling::td/button[text()='Clasament']
Or go up to the parent row first, then find the button:
//td[text()='Spania']/parent::tr//button[text()='Clasament']
3. The button has a direct attribute linking to "Spania"
If the button itself has a data attribute for the country:
<button data-country="Spania" class="btn">Clasament</button>
This is the simplest case—combine both conditions directly on the button element:
//button[@data-country='Spania' and text()='Clasament']
Pro Tip
If you're dealing with extra spaces or line breaks in the text, use contains() instead of exact matches for more flexibility:
//button[@data-country='Spania' and contains(text(), 'Clasament')]
内容的提问来源于stack exchange,提问作者Alex Dorha

