我发布了一个类似的问题,没有考虑到身体中的多行。我有一个像这样的html,我想提取" body" (使用Nokogiri):
html = %q|
<div class="content">
<h1>Title 1</h1>
Lorem ipsum 1
<h2>Title 2</h2>
Lorem ipsum 2
<h3>Title 3</h3>
<p>paragraph content 1</p>
<b>Lorem ipsum 3</b>
<p>paragraph content 2</p>
<h1>Title 4</h1>
Lorem ipsum 4
<h2>Title 5</h2>
Lorem ipsum 5
</div>
|
我想在每个标题标题下提取正文内容,并将它们放入一个数组中,如下所示:
[
"Lorem ipsum 1",
"Lorem ipsum 2",
"<p>paragraph content 1</p><b>Lorem ipsum 3</b><p>paragraph content 2</p>",
"Lorem ipsum 4",
"Lorem ipsum 5"
]
然而,当我这样做时:
Nokogiri::HTML(html).
css("div").
children.
reject{|e| e.name =~ /\Ah\d\z/}.
map{|e| e.to_html.strip}.reject(&:empty?)
我得到了这个数组:
[
"Lorem ipsum 1",
"Lorem ipsum 2",
"<p>paragraph content 1</p>",
"<b>Lorem ipsum 3</b>",
"<p>paragraph content 2</p>",
"Lorem ipsum 4",
"Lorem ipsum 5"
]
有没有办法提取多行&#34; body&#34;内容显示我想要的数组?
答案 0 :(得分:1)
Nokogiri::HTML(html)
.css("div").children
.slice_before{|e| e.name =~ /\Ah\d\z/}
.map{|a| a.drop(1).map{|e| e.to_html.strip}.join}.reject(&:empty?)