"Rubyによるクローラー開発技法"という本を見ながら簡易クローラーを作成しているのですが、うまくいきません。
Ruby
1# -*- coding: utf-8 -*- 2require 'cgi' 3require 'open-uri' 4require 'rss' 5require 'kconv' 6require 'webrick' 7 8class Site 9 def initialize(url:"", title:"") 10 @url, @title = url, title 11 end 12 attr_reader :url, :title 13 14 def page_source 15 @page_source ||= open(@url, &:read).toutf8 16 end 17 18 def output(formatter_klass) 19 formatter_klass.new(self).format(parse) 20 end 21end 22 23class SbcrTopics < Site 24 def parse 25 dates = page_source.scan(%r!(\d+)年 ?(\d+)月 ?(\d+)日<br />!) 26 url_titles = page_source.scan(%r!^<a href="(.+?)">(.+?)</a><br />!) 27 url_titles.zip(dates).map{|(aurl, atitle), 28 ymd|[CGI.unescapeHTML(aurl), 29 CGI.unescapeHTML(atitle), Time.local(*ymd)] 30 } 31 end 32end 33 34class Formatter 35 def initialize(site) 36 @url = site.url 37 @title = site.title 38 end 39 attr_reader :url, :title 40end 41 42class TextFormatter < Formatter 43 def format(url_title_time_ary) 44 s = "Title: #{title}\nURL: #{url}\n\n" 45 url_title_time_ary.each do |aurl, atitle, atime| 46 s << "* (#{atime})#{atitle}\n" 47 s << " #{aurl}\n" 48 end 49 s 50 end 51end 52 53class RSSFormatter < Formatter 54 def format(url_title_time_ary) 55 RSS::Maker.make("2.0") do |maker| 56 maker.channel.updated = Time.now.to_s 57 maker.channel.link = url 58 maker.channel.title = title 59 maker.channel.description = title 60 url_title_time_ary.each do |aurl, atitle, atime| 61 maker.items.new_item do |item| 62 item.link = aurl 63 item.title = atitle 64 item.updated = atime 65 item.description = atitle 66 end 67 end 68 end 69 end 70end 71 72class RSSServlet < WEBrick::HTTPServlet::AbstractServlet 73 def do_GET(req, res) 74 klass, opts = @options 75 res.body = klass.new(opts).output(RSSFormatter).to_s 76 res.content_type = "application/xml; charset=utf-8" 77 end 78end 79 80def start_server 81 srv = WEBrick::HTTPServer.new(:BindAddress => '127.0.0.1', :Port => 7777) 82 srv.mount('/rss.xml', RSSServlet, SbcrTopics, 83 url:"http://scrawler.sbcr.jp/samplepage.html", 84 title:"WWW.SBCR.JP トピックス") 85 # 場合によってはsrv.mount行を追加する 86 trap("INT"){ srv.shutdown } 87 srv.start 88end 89 90if ARGV.first == 'server' 91 start_server 92else 93 site = SbcrTopics.new( 94 url:"http://crawler.sbcr.jp/samplepage.html", 95 title:"WWW.SBCR.JP トピックス") 96 case ARGV.first 97 when "rss-output" 98 puts site.output RSSFormatter 99 when "text-output" 100 puts site.output TextFormatter 101 end 102end
コードは以上の通りです。
これを実行(ruby rssserver2.rb server)した状態で、ブラウザにてhttp://127.0.0.1:7777/rss.xmlに移動して見ると、
Internal Server Error
getaddrinfo: nodename nor servname provided, or not known
のように表示され、予想していたRSSの画面になりません。
何が原因なのでしょうか?わかる方がいらっしゃいましたら、ご教授宜しくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/09/16 14:58