html - 如何使用 Nokogiri 漂亮地打印 HTML?

标签 html ruby nokogiri pretty-print

我用 Ruby 编写了一个网络爬虫,我正在使用 Nokogiri::HTML 来解析页面。我需要将页面打印出来,在 IRB 中闲逛时,我注意到一个 pretty_print 方法。但是它需要一个参数,我不知道它想要什么。

我的爬虫正在缓存网页的 HTML 并将其写入本地计算机上的文件。我想“漂亮地打印”HTML,以便在我这样做时它看起来漂亮且格式正确。

最佳答案

@mislav 的回答有些错误。 Nokogiri 确实支持 pretty-print 如果你:

  • 将文档解析为 XML
  • 指示 Nokogiri 在解析期间忽略纯空白节点(“空白”)
  • 使用to_xhtmlto_xml 指定pretty-printing parameters

在行动中:

html = '<section>
<h1>Main Section 1</h1><p>Intro</p>
<section>
<h2>Subhead 1.1</h2><p>Meat</p><p>MOAR MEAT</p>
</section><section>
<h2>Subhead 1.2</h2><p>Meat</p>
</section></section>'

require 'nokogiri'
doc = Nokogiri::XML(html,&:noblanks)
puts doc
#=> <section>
#=>   <h1>Main Section 1</h1>
#=>   <p>Intro</p>
#=>   <section>
#=>     <h2>Subhead 1.1</h2>
#=>     <p>Meat</p>
#=>     <p>MOAR MEAT</p>
#=>   </section>
#=>   <section>
#=>     <h2>Subhead 1.2</h2>
#=>     <p>Meat</p>
#=>   </section>
#=> </section>

puts doc.to_xhtml( indent:3, indent_text:"." )
#=> <section>
#=> ...<h1>Main Section 1</h1>
#=> ...<p>Intro</p>
#=> ...<section>
#=> ......<h2>Subhead 1.1</h2>
#=> ......<p>Meat</p>
#=> ......<p>MOAR MEAT</p>
#=> ...</section>
#=> ...<section>
#=> ......<h2>Subhead 1.2</h2>
#=> ......<p>Meat</p>
#=> ...</section>
#=> </section>

关于html - 如何使用 Nokogiri 漂亮地打印 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1898829/

相关文章:

html - CSS 叠加关闭按钮响应

ruby - NoMethodError:8 的未定义方法 `type':Fixnum

ruby-on-rails - Ruby on Rails 嵌套属性没有保存到数据库中?

ruby - 获取标签后的文本,包含另一个文本

html - 使我的移动 html 全屏

javascript - JQuery 无法重新排序列表中的元素;怎么修?

javascript - onload 操作仅在基于 WebKit 的 Chrome 上的同一页面上运行一次

ruby - 按另一个数组对数组进行排序

ruby - Nokogiri(在 Ubuntu 上)的可靠安装过程是什么?

ruby - 如何单击 Mechanize 和 Nokogiri 中的链接?