【问题标题】:Find and replace HTML tags查找和替换 HTML 标签
【发布时间】:2018-11-22 13:29:49
【问题描述】:

我有以下 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 标签?我可以使用Nokogiri gem。

【问题讨论】:

    标签: html ruby string parsing nokogiri


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 这个解决方案真的很优雅!非常感谢!
    • 你知道如何进行 css-search 以找到具有 id 和类的 div 吗?示例:
      XXX
      ?
    • frag.xpath("//div[@id='foo' and @class='bar']")
    • 你知道如何改变 div 标签的类值吗?示例:
      XXX
      这里我想将(class='bar' 改为 class='test')?
    【解决方案2】:

    似乎这样工作正常:

    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>
    

    【讨论】:

      【解决方案3】:
      #!/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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-19
        • 2022-01-06
        • 2017-01-08
        • 2017-12-31
        • 1970-01-01
        • 1970-01-01
        • 2010-10-01
        • 1970-01-01
        相关资源
        最近更新 更多