2012-10-04 87 views
5

我試圖編寫一個簡單的網頁在紅寶石刮。 它的工作原理,直到29號網址,然後我得到這個錯誤信息:RUBY - 網絡抓取 - (OpenURI :: HTTPError)

C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:346:in `open_http': 500 Internal Server Er 
ror (OpenURI::HTTPError) 
     from C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:775:in `buffer_open' 
     from C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:203:in `block in open_loop' 
     from C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:201:in `catch' 
     from C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:201:in `open_loop' 
     from C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:146:in `open_uri' 
     from C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:677:in `open' 
     from C:/Ruby193/lib/ruby/1.9.1/open-uri.rb:33:in `open' 
     from test.rb:24:in `block (2 levels) in <main>' 
     from test.rb:18:in `each' 
     from test.rb:18:in `block in <main>' 
     from test.rb:14:in `each' 
     from test.rb:14:in `<main>' 

我的代碼:

require 'rubygems' 
require 'nokogiri' 
require 'open-uri' 

aFile=File.new('data.txt', 'w') 

ag = 0 
    for i in 1..40 do 
    agenzie = ag + 1 

    #change url parameter 

    url = "http://www.infotrav.it/dettaglio.do?sort=*RICOVIAGGI*&codAgenzia=" + "#{ ag }" 
    doc = Nokogiri::HTML(open(url)) 
    aFile=File.open('data.txt', 'a') 
    aFile.write(doc.at_css("table").text) 
    aFile.close 
    end 

你有一些想法去解決呢? 謝謝!

回答

3

在這裏,讓我清理你:

File.open('data.txt', 'w') do |aFile| 
    (1..40).each do |ag| 
    url = "http://www.infotrav.it/dettaglio.do?sort=*RICOVIAGGI*&codAgenzia=#{ag}" 
    response = open(url) rescue nil 
    next unless response 
    doc = Nokogiri::HTML(response) 
    aFile << doc.at_css("table").text 
    end 
end 

筆記:

  • 使用塊風格File.open意味着當 塊退出
  • 使用該文件將關閉本身每個迭代而不是for循環
+0

謝謝我是一個紅寶石新手... – jackkkk

3

如果你不能修復遠程服務器上的問題,嘗試從錯誤營救,並繼續拆解:

begin 
    doc = Nokogiri::HTML(open(url)) 
    aFile=File.open('data.txt', 'a') 
    aFile.write(doc.at_css("table").text) 
    aFile.close 
rescue => e 
    puts e.message 
end 
4

的代碼有一個小錯字。它應該是ag = ag + 1而不是agenzie = ag + 1。我假設你在將代碼複製到stackoverflow時發生了錯誤,因爲代碼不會與錯字一起工作。

我能夠在本地運行代碼,並得到相同的錯誤。在http://www.infotrav.it網站上找不到url being accessed(codAgenzia = 30時);它返回一個HTTP錯誤500

所以,問題不在於你的代碼,但由於slivu在他的回答中提到的遠程服務器(http://www.infotrav.it

,你應該救錯誤並繼續刮。

+0

Prakash,現在我明白了..問題是服務器上的htt p://www.infotrav.it/dettaglio.do?sort =%2aRICOVIAGGI%2a&codAgenzia = 30檢索一些錯誤! 謝謝! – jackkkk

+0

不客氣!不要忘記將答案標記爲已接受。 –