加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 从标记中提取HTML5数据属性

发布时间:2020-12-16 21:02:37 所属栏目:百科 来源:网络整理
导读:我想从标签中提取所有 HTML5数据属性,就像 this jQuery plugin一样. 例如,给定: span data-age="50" data-location="London" class="highlight"Joe Bloggs/span 我想得到一个哈希: { 'data-age' = '50','data-location' = 'London' } 我最初希望使用通配符
我想从标签中提取所有 HTML5数据属性,就像 this jQuery plugin一样.

例如,给定:

<span data-age="50" data-location="London" class="highlight">Joe Bloggs</span>

我想得到一个哈希:

{ 'data-age' => '50','data-location' => 'London' }

我最初希望使用通配符作为我的CSS选择器的一部分,例如

Nokogiri(html).css('span[@data-*]').size

但似乎不支持.

解决方法

选项1:抓取所有数据元素

如果您只需要列出所有页面的数据元素,那么这是一个单行:

Hash[doc.xpath("//span/@*[starts-with(name(),'data-')]").map{|e| [e.name,e.value]}]

输出:

{"data-age"=>"50","data-location"=>"London"}

选项2:按标签对结果进行分组

如果要按标记对结果进行分组(可能需要对每个标记进行其他处理),可以执行以下操作:

tags = []
datasets = "@*[starts-with(name(),'data-')]"

#If you want any element,replace "span" with "*"
doc.xpath("//span[#{datasets}]").each do |tag|
    tags << Hash[tag.xpath(datasets).map{|a| [a.name,a.value]}]
end

然后tags是一个包含键值哈希对的数组,按标记分组.

选项3:jQuery数据集插件之类的行为

如果您更喜欢类似插件的方法,下面将为您提供每个Nokogiri节点上的数据集方法.

module Nokogiri
  module XML
    class Node
      def dataset
        Hash[self.xpath("@*[starts-with(name(),'data-')]").map{|a| [a.name,a.value]}]
      end
    end
  end
end

然后,您可以找到单个元素的数据集:

doc.at_css("span").dataset

或者获取一组元素的数据集:

doc.css("span").map(&:dataset)

例:

以下是上述数据集方法的行为.给出HTML中的以下行:

<span data-age="50" data-location="London" class="highlight">Joe Bloggs</span>
<span data-age="40" data-location="Oxford" class="highlight">Jim Foggs</span>

输出将是:

[
 {"data-location"=>"London","data-age"=>"50"},{"data-location"=>"Oxford","data-age"=>"40"}
]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读