如何为指定HTML代码编写XPath以提取数值177?
It looks like the error you're hitting is because your XPath expressions are trying to select text nodes directly, but the tool you're using requires selecting elements first (not raw text nodes). Let's fix that.
First, let's recap the HTML structure we're working with:
<p> <b>Inventory:</b> 177<br> <b>UNIT:(12 per unit)</b> </p>
Approach 1: Select the Parent Element, Then Extract and Parse Text
This is the most reliable method if your tool doesn't allow selecting text nodes directly.
First, target the correct
<p>element with an XPath that selects elements (not text):- If you know the exact position (like your first attempt), use:
//*[@id='product_addtocart_form']/div[3]/p[2] - Or, to make it more robust (not dependent on position), use:
//p[b[text()='Inventory:']]
This selects the
<p>element that contains a<b>with the text "Inventory:".- If you know the exact position (like your first attempt), use:
Extract the text content from this
<p>element (it will be something like " Inventory: 177 UNIT:(12 per unit) ").Parse the number 177 from the text. For example:
- Split the text on "Inventory:" to get the part after it:
177 UNIT:(12 per unit) - Trim whitespace, then split on spaces to get the first token:
177
- Split the text on "Inventory:" to get the part after it:
Approach 2: Select the Specific Text Node (If Your Tool Allows It)
If your scraping tool or library supports selecting text nodes (some do, even if yours threw an error initially), you can use this XPath to target the text node containing 177 directly:
//p/b[1]/following-sibling::text()[1]
This selects the text node that comes right after the first <b> element inside the <p>. You can then trim whitespace from this text to get "177".
Why Your Previous XPaths Failed
//*[@id='product_addtocart_form']/div[3]/p[2]/text(): This tries to select text nodes directly under the<p>, but your tool expects an element as the result.//p/b[1]/text(): This selects the text inside the first<b>("Inventory:"), which isn't the value you want, and again, if the tool expects an element, it will throw an error.
内容的提问来源于stack exchange,提问作者suvarnareddy

