2009-03-04 25 views
12

Aşağıdaki HTML'ye sahibim:Nokogiri (RubyGem): HTML etiketlerini bul ve değiştir

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

... ve RubyGem Nokogiri (hpricot yerine) kullanarak, onu aşağıdaki HTML olarak değiştirmek istiyorum:

<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> 

Başka bir deyişle: Nokogiri'yi kullanarak belirli HTML etiketlerini nasıl bulabilir ve değiştirebilirim? Onları nasıl bulacağımı biliyorum (css anahtar kelimeleri kullanarak), ancak belgeyi ayrıştırırken bunları nasıl değiştireceğimi bilmiyorum.

Yardımlarınız için teşekkürler!

cevap

18

bu deneyin:

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

Bu çözüm gerçekten zarif! Çok teşekkürler! – Javier

+0

Bir kimlik ve bir sınıfa sahip bir div bulmak için css-araması yapmayı biliyor musunuz? Örnek:

XXX
? – Javier

+0

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

15

görünüyor bu hak çalışır gibi:

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

Bu çözüm de çalışıyor. – 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

Bu çözüm çalışıyor. – Javier