XPath Selector -- 一个 XPath 选择器库,快速节点获取数据
Tính đến
Script này sẽ không được không được cài đặt trực tiếp. Nó là một thư viện cho các script khác để bao gồm các chỉ thị meta
// @require https://update.greasyfork.org/scripts/559142/1715003/DXPath%20Selector%20%E4%B8%80%E4%B8%AA%20XPath%20%E9%80%89%E6%8B%A9%E5%99%A8%E5%BA%93%EF%BC%8C%E5%BF%AB%E9%80%9F%E8%8A%82%E7%82%B9%E8%8E%B7%E5%8F%96%E6%95%B0%E6%8D%AE.js
一个 XPath 选择器库,快速节点获取数据
// @require https://**/xpath-selector.js?*
Options 参数说明:
| 参数名 | 类型 | 是否必填 | 默认值 | 说明 |
|---|---|---|---|---|
expression |
string | 是 | 要获取的节点的 XPath 表达式 | |
returnType |
string | 是 | 获取结果的类型,可选值:string、strings、number、numbers、boolean、nodes、first-node、map、array、all-results |
|
node |
Node | 否 | document |
要搜索的节点 |
获取 title 节点的文本内容
const title = xpathSelector({
expression: '//title/text()',
returnType: 'string'
})
console.log(title) // hello world
获取所有 p 节点的文本内容
const pList = xpathSelector({
expression: '//p/text()',
returnType: 'strings'
})
console.log(pList) // ['hello', 'world']
统计所有 a 节点的个数
const aCount = xpathSelector({
expression: 'count(//a)',
returnType: 'number'
})
console.log(aCount) // 2
判断是否存在 section 节点
const hasSection = xpathSelector({
expression: 'boolean(//section)',
returnType: 'boolean'
})
console.log(hasSection) // true
获取全部的 a 节点
const aList = xpathSelector({
expression: '//a',
returnType: 'nodes'
})
console.log(aList) // [<a>hello</a>, <a>world</a>]
获取第一个 a 节点
const firstA = xpathSelector({
expression: '//a',
returnType: 'first-node'
})
console.log(firstA) // <a>hello</a>
获取 html 节点的全部属性
const htmlAttributes = xpathSelector({
expression: `map:merge(
for $attr in //html/@*
return map:entry(local-name($attr), string($attr))
)`,
returnType: 'map'
})
console.log(htmlAttributes) // {lang: "en", charset: "UTF-8"}
GreasyFork 或者 ScriptCat 回复不及时,问题反馈推荐直接在 Github 提 Issue。
如果觉得本脚本对你有帮助,欢迎点个 ⭐ Star 支持一下!