2009-03-04 3 views
12

Ich habe folgende HTML:Nokogiri (RubyGem): Suchen und Ersetzen von HTML-Tags

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

... und durch die RubyGem mit Nokogiri (a hpricot Ersatz), Ich mag würde es in die sich ändern folgende 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> 

Mit anderen Worten: Wie kann ich bestimmte HTML-Tags mit Nokogiri finden und ersetzen? Ich weiß, wie man sie findet (mit CSS-Schlüsselwörtern), aber ich weiß nicht, wie ich sie beim Parsen des Dokuments ersetzen kann.

Danke für Ihre Hilfe!

Antwort

18

Versuchen Sie folgendes:

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

Diese Lösung ist wirklich elegant! Danke vielmals! – Javier

+0

Wissen Sie, wie man eine CSS-Suche durchführt, um ein div mit einer ID und einer Klasse zu finden? Beispiel:

XXX
? – Javier

+0

frag.xpath ("// div [@ id = 'foo' und @ class = 'bar']") – SimonV

15

Scheint, wie das funktioniert recht:

require 'rubygems' 
require 'nokogiri' 

markup = Nokogiri::HTML.parse(<<-somehtml) 
<html> 
<body> 
<h1>Foo</h1> 
<p>The quick brown fox.</p> 
<h1>Bar</h1> 
<p>Jumps over the lazy dog.</p> 
</body> 
</html> 
somehtml 

markup.css('h1').each do |el| 
    el.name = 'p' 
    el.set_attribute('class','title') 
end 

puts markup.to_html 
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
# >> <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> 
+0

Diese Lösung funktioniert auch. – Javier

6
#!/usr/bin/env ruby 
require 'rubygems' 
gem 'nokogiri', '~> 1.2.1' 
require 'nokogiri' 

doc = Nokogiri::HTML.parse <<-HERE 
    <html> 
    <body> 
     <h1>Foo</h1> 
     <p>The quick brown fox.</p> 
     <h1>Bar</h1> 
     <p>Jumps over the lazy dog.</p> 
    </body> 
    </html> 
HERE 

doc.search('h1').each do |heading| 
    heading.name = 'p' 
    heading['class'] = 'title' 
end 

puts doc.to_html 
+0

Diese Lösung funktioniert. – Javier