문제

다음 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로 변경하고 싶습니다.

<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 태그를 어떻게 찾아 교체 할 수 있습니까? 나는 그것을 사용할 수있다 노코 시리 보석.

도움이 되었습니까?

해결책

이 시도:

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

다른 팁

이것이 제대로 작동하는 것 같습니다.

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>
#!/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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top