我用 Ruby 编写了一个网络爬虫,我正在使用 Nokogiri::HTML
来解析页面。我需要将页面打印出来,在 IRB 中闲逛时,我注意到一个 pretty_print
方法。但是它需要一个参数,我不知道它想要什么。
我的爬虫正在缓存网页的 HTML 并将其写入本地计算机上的文件。我想“漂亮地打印”HTML,以便在我这样做时它看起来漂亮且格式正确。
最佳答案
@mislav 的回答有些错误。 Nokogiri 确实支持 pretty-print 如果你:
- 将文档解析为 XML
- 指示 Nokogiri 在解析期间忽略纯空白节点(“空白”)
- 使用
to_xhtml
或to_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/