查找并替换HTML标签 [英] Find and replace HTML tags

查看:112
本文介绍了查找并替换HTML标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML:

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

我想将其更改为以下HTML:

I'd like to change it into the following 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>

如何查找和替换某些HTML标签?我可以使用 Nokogiri 宝石.

How can I find and replace certain HTML tags? I can use the Nokogiri gem.

推荐答案

尝试一下:

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") }

这篇关于查找并替换HTML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆