2009-03-04 4 views
12

Nokogiri (RubyGem) : 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 키워드를 사용하여) 찾는 방법을 안다. 그러나 나는 문서를 파싱하는 동안 그것들을 대체하는 방법을 모른다.

당신의 도움에 감사드립니다!

답변

18

이 시도 :

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

이 솔루션은 정말 우아! 고마워요! – Javier

+0

id와 클래스가있는 div를 찾기 위해 CSS 검색을 수행하는 방법을 알고 있습니까? 예 :

XXX
? – Javier

+0

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

15

이 보인다이 잘 작동처럼 :

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

이 솔루션도 효과가 있습니다. – 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

이 솔루션이 효과적입니다. – Javier