如何为指定HTML代码构造Locator?基于XPath定位Job Duration及li元素列表
Got it, let's break this down for you. Locating the Job Duration-related elements and grabbing its list items is totally doable with XPath—here's how to approach it step by step:
First, let's recap your target HTML for reference:
Job Duration :
1. Locating the Job Duration container or header element
If you want to target the entire section's wrapper (the div that holds both the header and list), use one of these specific XPath expressions:
- Anchor to the
h3text to find its parent div://div[h3[text()='Job Duration :']] - Add the div's class for extra specificity (in case there are other similar divs on the page):
//div[@class='box rounded6' and h3[text()='Job Duration :']]
If you only need the header element itself ("Job Duration :"), use this simple XPath:
//h3[text()='Job Duration :']
2. Fetching all li elements under Job Duration
Once you've anchored to the section, you can chain XPath to grab all list items. Here are three reliable methods:
Option 1: Target li elements via the h3's sibling ul
Since the ul sits right after the h3, you can use the sibling axis to jump directly to it:
//h3[text()='Job Duration :']/following-sibling::ul/li
Option 2: Drill down from the container div
This is great for ensuring you're only pulling li elements from the correct Job Duration section (avoids conflicts with other lists):
//div[h3[text()='Job Duration :']]/ul/li
Option 3: Extract the text inside each li (if needed)
If your goal is to get the actual text values like "Contract" or "Full Time" instead of just the elements, adjust the XPath to target the text node inside the label:
//div[h3[text()='Job Duration :']]/ul/li/label/text()
All these expressions work reliably with your given HTML. The key here is using the unique h3 text to anchor your XPath—this is more robust than relying solely on classes, which might be reused elsewhere on the page.
内容的提问来源于stack exchange,提问作者ViTest

