上一主题 下一主题
ScriptCat,新一代的脚本管理器脚本站,与全世界分享你的用户脚本油猴脚本开发指南教程目录
返回列表 发新帖

利用 XPath 快速获取节点数据

[复制链接]
  • TA的每日心情
    开心
    3 小时前
  • 签到天数: 2 天

    [LV.1]初来乍到

    3

    主题

    4

    回帖

    17

    积分

    助理工程师

    积分
    17
    发表于 3 小时前 | 显示全部楼层 | 阅读模式

    如何使用? 库问题反馈 给库评分 查看代码

    本帖最后由 xiaohuohumax 于 2025-12-17 12:01 编辑

    📖 使用方式

    ✍ 添加元数据

    // @require      https://**/xpath-selector.js?*

    📥 参数说明

    Options 参数说明:

    参数名 类型 是否必填 默认值 说明
    expression string 要获取的节点的 XPath 表达式
    returnType string 获取结果的类型,可选值:stringstringsnumbernumbersbooleannodesfirst-nodemaparrayall-results
    node Node document 要搜索的节点

    📦 使用示例

    <!DOCTYPE html>
    <html lang="en" charset="UTF-8">
    <head>
        <title>hello world</title>
    </head>
    <body>
        <p>hello</p>
        <p>world</p>
        <a href="#">hello</a>
        <a href="#">world</a>
        <section>
            <!-- section内容 -->
        </section>
    </body>
    </html>

    获取 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"}

    获取自定义 html 节点的 title 节点的文本内容

    const customHtmlTitle = xpathSelector({
      expression: '//title/text()',
      node: new DOMParser().parseFromString('<html><title>Hello</title></html>', 'text/html'),
      returnType: 'string',
    })
    console.log(customHtmlTitle) // Hello

    🧩 依赖项目

    发表回复

    本版积分规则

    快速回复 返回顶部 返回列表