Jar*_*sen 23 html ruby pretty-print nokogiri
我在Ruby中编写了一个Web爬虫,我正在使用它Nokogiri::HTML来解析页面.我需要打印页面,在IRB中乱搞时我注意到了一种pretty_print方法.然而,它需要一个参数,我无法弄清楚它想要什么.
我的抓取工具正在缓存网页的HTML并将其写入本地计算机上的文件.我想"漂亮地打印"HTML,以便它在我这样做时看起来很好并且格式正确.
Phr*_*ogz 75
@mislav的答案有点不对劲.如果您:Nokogiri支持漂亮打印:
to_xhtml或to_xml指定漂亮的打印参数在行动:
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>
Run Code Online (Sandbox Code Playgroud)
mis*_*lav 21
通过HTML页面的"漂亮打印",我认为你的意思是你希望用适当的缩进重新格式化HTML结构.Nokogiri不支持这一点; pretty_printmethod用于"pp"库,输出仅用于调试.
有几个项目能够很好地理解HTML,能够在不破坏实际重要的空白(着名的HTML Tidy)的情况下对其进行重新格式化,但通过谷歌搜索,我发现这篇文章名为"使用Nokogiri和XSLT轻松打印XHTML".
归结为:
xsl = Nokogiri::XSLT(File.open("pretty_print.xsl"))
html = Nokogiri(File.open("source.html"))
puts xsl.apply_to(html).to_s
Run Code Online (Sandbox Code Playgroud)
当然,它要求您将链接的xsl文件下载到文件系统.我在我的机器上很快就尝试过,它就像一个魅力.
这对我有用:
pretty_html = Nokogiri::HTML(html).to_xhtml(indent: 3)
Run Code Online (Sandbox Code Playgroud)
我尝试了上面的REXML版本,但它损坏了我的一些文档.我讨厌将xslt带入一个新项目.两人都觉得过时了.:)
| 归档时间: |
|
| 查看次数: |
25936 次 |
| 最近记录: |