我正在使用 Nokogiri 来抓取网页。很少有 url 需要被猜测,当它们不存在时返回 404 not found 错误。有没有办法捕获这个异常?
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
最佳答案
它不起作用,因为您没有拯救在发现 404 状态时引发错误的部分代码(它是 open(url)
调用)。以下代码应该有效:
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
顺便说一句,关于拯救Exception
:
Why is it a bad style to `rescue Exception => e` in Ruby?
关于ruby - 如何处理 Nokogiri 中的 404 not found 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18270596/