2013-08-16 31 views
8

我正在使用Nokogiri來抓取網頁。很少有urls需要被猜測,並且當它們不存在時返回404沒有發現錯誤。有沒有辦法捕捉這個異常?如何處理404在Nokogiri中找不到錯誤

http://yoursite/page/38475 #=> page number 38475 doesn't exist 

我試過以下哪些方法沒有奏效。

url = "http://yoursite/page/38475" 
doc = Nokogiri::HTML(open(url)) do 
    begin 
    rescue Exception => e 
     puts "Try again later" 
    end 
end 

回答

18

它不工作,因爲你沒有搶救的部分代碼(這是open(url)調用)在尋找404種狀態的情況下引發錯誤。下面的代碼應該工作:

url = 'http://yoursite/page/38475' 
begin 
    file = open(url) 
    doc = Nokogiri::HTML(file) do 
    # handle doc 
    end 
rescue OpenURI::HTTPError => e 
    if e.message == '404 Not Found' 
    # handle 404 error 
    else 
    raise e 
    end 
end 

BTW,大約搶救ExceptionWhy is it a bad style to `rescue Exception => e` in Ruby?

+0

我的事情是更好地使用''e.io.not_found – Calin