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

ruby-on-rails – Nokogiri(RubyGem):查找和替换HTML标签

发布时间:2020-12-16 20:03:56 所属栏目:百科 来源:网络整理
导读:我有以下 HTML: htmlbodyh1Foo/h1pThe quick brown fox./ph1Bar/h1pJumps over the lazy dog./p/body/html …并通过使用RubyGem Nokogiri(更换为hpricot),我想将其更改为以下HTML: htmlbodyp class="title"Foo/ppThe quick brown fox./pp class="title"Bar
我有以下 HTML:
<html>
<body>
<h1>Foo</h1>
<p>The quick brown fox.</p>
<h1>Bar</h1>
<p>Jumps over the lazy dog.</p>
</body>
</html>

…并通过使用RubyGem Nokogiri(更换为hpricot),我想将其更改为以下HTML:

<html>
<body>
<p class="title">Foo</p>
<p>The quick brown fox.</p>
<p class="title">Bar</p>
<p>Jumps over the lazy dog.</p>
</body>
</html>

换句话说:如何使用Nokogiri找到并替换某些HTML标签?我知道如何找到它们(使用css关键字),但我不知道如何在解析文档时替换它们.

谢谢你的帮助!

解决方法

尝试这个:
require 'nokogiri'

html_text = "<html><body><h1>Foo</h1><p>The quick brown fox.</p><h1>Bar</h1><p>Jumps over the lazy dog.</p></body></html>"

frag = Nokogiri::HTML(html_text)
frag.xpath("//h1").each { |div|  div.name= "p"; div.set_attribute("class","title") }

(编辑:李大同)

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

    推荐文章
      热点阅读