0

こんにちは私はnokogiriに不慣れで、さまざまなツリー構造を持つHTMLドキュメントを解析しようとしています。それを解析する方法についての提案は素晴らしいでしょう。このページのすべてのテキストをキャプチャしたいと思います。

<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>  

私はこれを試しましたが、それはそれぞれの完全な配列を出力するだけであり、「スタッフ」の部分に到達する方法さえわかりません。

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         

ヘルプをいただければ幸いです。

4

1 に答える 1

0

そのようなものはあなたの与えられた文書構造を解析するでしょう:

データ

<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>

コード:

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

印刷します:

[{"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"}]}]
于 2013-03-14T05:01:49.083 に答える