You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chrome开发者控制台提取XPath匹配的href属性值?

Got it, let's sort out how to pull those href values into a clean array right in Chrome's DevTools Console! Here are a few simple, reliable ways to do this:

Method 1: Convert the XPath result to an array and map values

The $x() function returns an iterable collection of attribute nodes (each representing an href attribute). We can turn this into a proper array and extract the value property from each node:

Array.from($x('/html/body/a/@href')).map(attrNode => attrNode.value)

This works because Array.from() converts the XPath result into a standard array, then map() loops through each attribute node to grab its actual string value.

Method 2: Shorter syntax with the spread operator

If you prefer more concise code, use the spread operator (...) to turn the XPath result into an array instead:

[...$x('/html/body/a/@href')].map(attrNode => attrNode.value)

Same end result, just a snappier way to write it.

Bonus: A more intuitive XPath approach

Instead of targeting the attribute directly in XPath, you can select the <a> elements themselves and extract the href attribute directly from the DOM elements. This might feel more straightforward for many developers:

// Gets the full absolute URL (e.g., "https://your-site.com/link1.html")
$x('/html/body/a').map(link => link.href)

// Gets the original relative path exactly as written in the HTML
$x('/html/body/a').map(link => link.getAttribute('href'))

The second line here will give you exactly the array you want: ["link1.html", "link2.html"].

内容的提问来源于stack exchange,提问作者me.at.coding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:53:14