我有以下HTML:
Foo
The quick brown fox.
Bar
Jumps over the lazy dog.
我想将其更改为以下HTML:
Foo
The quick brown fox.
Bar
Jumps over the lazy dog.
如何查找和替换某些HTML标记?我可以使用Nokogiri宝石.
试试这个:
require 'nokogiri' html_text = "Foo
The quick brown fox.
Bar
Jumps over the lazy dog.
" frag = Nokogiri::HTML(html_text) frag.xpath("//h1").each { |div| div.name= "p"; div.set_attribute("class" , "title") }
看起来这样可行:
require 'rubygems' require 'nokogiri' markup = Nokogiri::HTML.parse(<<-somehtml)Foo
The quick brown fox.
Bar
Jumps over the lazy dog.
somehtml markup.css('h1').each do |el| el.name = 'p' el.set_attribute('class','title') end puts markup.to_html # >> # >> # >>Foo
# >>The quick brown fox.
# >>Bar
# >>Jumps over the lazy dog.
# >>
#!/usr/bin/env ruby require 'rubygems' gem 'nokogiri', '~> 1.2.1' require 'nokogiri' doc = Nokogiri::HTML.parse <<-HEREFoo
The quick brown fox.
Bar
Jumps over the lazy dog.
HERE doc.search('h1').each do |heading| heading.name = 'p' heading['class'] = 'title' end puts doc.to_html