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

在Nokogiri中如何获取指定标签的实例序号

解决方案

你可以通过正则匹配或者字符串切割两种方式快速提取目标数值,具体实现如下:

方法1:正则表达式匹配(通用性最高)

直接匹配section[和]之间的数字即可,不管路径其他部分怎么变化都能正常提取。
示例代码(以Python为例):

import re

xpath_str = "/html/head/base/link/body/div/br/form/hr/chapter[1]/section[1]/ul/li[1]/a"
match_res = re.search(r'section\[(\d+)\]', xpath_str)
if match_res:
    section_index = match_res.group(1)
    print(section_index) # 输出结果为1

如果需要提取其他标签的序号,只要把正则里的section替换成对应标签名即可。

方法2:字符串切割(适合固定格式路径)

如果你的XPath路径结构固定,也可以先按/切割成片段,找到对应section的片段后再提取数字:

xpath_str = "/html/head/base/link/body/div/br/form/hr/chapter[1]/section[1]/ul/li[1]/a"
path_parts = xpath_str.split('/')
for part in path_parts:
    if part.startswith('section['):
        section_index = part.strip('section[]')
        print(section_index) # 输出结果为1
        break

内容的提问来源于stack exchange,提问作者Benjamin Philip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:18:04