0

私はこのコードを書きました。これは、ジョブの説明のリストを出力します(デンマーク語)。正常に動作しますが、出力を少し変更したいと思います。ジョブがネストされているため、関数は再帰的ですが、出力にはネストが表示されません。

次のような出力を表示するように関数を構成するにはどうすればよいですか。

ジョブ1-
ジョブ1.1-
ジョブ1.2-
ジョブ1.2.1

等々...

require 'nokogiri'
require 'open-uri'


def crawl(url)

  basePath = 'http://www.ug.dk'
  doc = Nokogiri::HTML(open(basePath + url))

  doc.css('.maplist li').each do |listitem|

    listitem.css('.txt').each do |txt|
      puts txt.content
    end

    listitem.css('a[href]').each do |link|
      crawl(link['href'])
    end

  end

end


crawl('/Job.aspx')
4

2 に答える 2

1
require 'nokogiri'
require 'open-uri'

def crawl(url, nesting_level = 0)    
  basePath = 'http://www.ug.dk'

  doc = Nokogiri::HTML(open(basePath + url))

  doc.css('.maplist li').each do |listitem|
    listitem.css('.txt').each do |txt|
      puts " " * nesting_level + txt.content
    end

    listitem.css('a[href]').each do |link|
      crawl(link['href'], nesting_level + 1)
    end
  end    
end

crawl('/Job.aspx')
于 2013-01-31T09:54:15.570 に答える
1

2つのオプションがあります。

  1. 現在のレベルを示すために、再帰関数に追加の引数を渡します。値を0に初期化し、関数を呼び出すたびにこの値をインクリメントします。このようなもの:

    def crawl(url, level)
    
      basePath = 'http://www.ug.dk'
      doc = Nokogiri::HTML(open(basePath + url))
    
      doc.css('.maplist li').each do |listitem|
    
        listitem.css('.txt').each do |txt|
          puts txt.content
        end
    
        listitem.css('a[href]').each do |link|
          crawl(link['href'], level + 1)
        end
    
      end
    
    end
    
  2. callerコールスタックを保持する配列を利用します。この配列のサイズを使用して、現在の再帰のレベルを示します。

     def try
       puts caller.inspect
     end
    
     try 
    

個人的には読みやすいように最初のバージョンに固執しますが、インターフェイスを変更する必要があります。

于 2013-01-31T09:54:25.650 に答える