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

Ruby Nokogiri报Tag figure无效错误,但HTML无明显问题

Nokogiri解析HTML提示figure标签无效的解决办法

你遇到的<figure>标签无效错误,原因是当前使用的是Nokogiri的HTML4解析器,而<figure>是HTML5新增标签,HTML4规范中没有定义该标签,因此解析器判定它无效。浏览器对HTML5兼容性较好,能正常识别这段代码,但Nokogiri默认的HTML4解析器遵循旧规范,会抛出语法错误。

以下是两种解决办法:

  • 改用HTML5解析器
    Nokogiri 1.10及以上版本支持HTML5解析,直接使用Nokogiri::HTML5即可处理包含HTML5标签的代码:

    require 'nokogiri'
    html_content = <<~HTML
      <div class="media">
        <figure id="post-image-figure-8" class="post-image-figure" style="max-width: 50%; ">
          <img src="/file8-thumbl.jpg" class="post-image img-no-border" id="post-image-8" style="cursor: pointer; max-width: 100%;" onclick="openPostIMG(8)" data-url="/file8.jpg" data-width="960" data-height="540" data-id="8">
        </figure>
      </div>
    HTML
    doc = Nokogiri::HTML5(html_content)
    

    若安装时出现依赖问题,可先安装系统依赖(如Ubuntu下执行sudo apt install libxml2-dev libxslt-dev),再确保Nokogiri版本符合要求。

  • 启用解析器的恢复模式
    若不想切换到HTML5解析器,可开启recover选项让HTML4解析器忽略未知标签错误:

    require 'nokogiri'
    html_content = <<~HTML
      <div class="media">
        <figure id="post-image-figure-8" class="post-image-figure" style="max-width: 50%; ">
          <img src="/file8-thumbl.jpg" class="post-image img-no-border" id="post-image-8" style="cursor: pointer; max-width: 100%;" onclick="openPostIMG(8)" data-url="/file8.jpg" data-width="960" data-height="540" data-id="8">
        </figure>
      </div>
    HTML
    # 方式一:指定ParseOptions
    doc = Nokogiri::HTML(html_content, nil, nil, Nokogiri::XML::ParseOptions::RECOVER)
    # 方式二:简写形式
    # doc = Nokogiri::HTML(html_content, parse_options: :recover)
    

    开启该选项后,解析器会跳过未知标签的错误提示,继续完成HTML内容的解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:47:12