简体   繁体   中英

parse html tree with nested loops using nokogiri

Hi I'm new to nokogiri and trying to parse an HTML document with a varied tree structure. Any suggestions on how to go about parsing it would be great. I'd like to capture all the text on this page.

<div class = "main"> Title</div>
<div class = "subTopic">
    <span = "highlight">Sub Topic</span>Stuff
</div>

<div class = "main"> Another Title</div>
<div class = "subTopic">
    <span class = "highlight">Sub Topic Title I</span>Stuff<br>
    <span class = "highlight">Sub Topic Title II</span>Stuff<br>
    <span class = "highlight">Sub Topic Title III</span>Stuff<br>
</div>  

I tried this but it just puts out each full array and I'm not even sure how to get to the "Stuff" part.

content = Nokogiri::HTML(open(@url))
content.css('div.main').each do |m|
    puts m .text
    content.css('div.subTopic').each do |s|
        puts s.text
        content.css('span.highlight').each do |h|
            puts h.text
        end
    end
end         

Help will be appreciated.

Something like that would parse your give document structure:

Data

<div class="main"> Title</div>
<div class="subTopic">
    <span class="highlight">Sub Topic</span>Stuff
</div>

<div class = "main"> Another Title</div>
<div class = "subTopic">
    <span class = "highlight">Sub Topic Title I</span>Stuff<br>
    <span class = "highlight">Sub Topic Title II</span>Stuff<br>
    <span class = "highlight">Sub Topic Title III</span>Stuff<br>
</div>

Code:

require 'nokogiri'
require 'pp'

content = Nokogiri::HTML(File.read('text.txt'));

topics = content.css('div.main').map do |m|
    topic={}
    topic['title'] = m.text.strip
    topic['highlights'] = m.xpath('following-sibling::div[@class=\'subTopic\'][1]').css('span.highlight').map do |h|
      topic_highlight = {}
      topic_highlight['highlight'] = h.text.strip
      topic_highlight['text'] = h.xpath('following-sibling::text()[1]').text.strip
      topic_highlight
    end
    topic
end

pp topics

Will print:

[{"title"=>"Title",
  "highlights"=>[{"highlight"=>"Sub Topic", "text"=>"Stuff"}]},
 {"title"=>"Another Title",
  "highlights"=>
   [{"highlight"=>"Sub Topic Title I", "text"=>"Stuff"},
    {"highlight"=>"Sub Topic Title II", "text"=>"Stuff"},
    {"highlight"=>"Sub Topic Title III", "text"=>"Stuff"}]}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM