我正在实现一个需要抓取网站的工具。我使用 anemone 进行爬行,并在每个 anemone 的页面上使用样板管和 Nokogiri 来管理 HTML 格式等。
我的问题是:如果我收到 500 Internal Server Error,它会使 Nokogiri 失败,因为没有页面。
Anemone.crawl(name) do |anemone|
anemone.on_every_page do |page|
if not (page.nil? && page.not_found?)
result = Boilerpipe.extract(page.url, {:output => :htmlFragment, :extractor => :ArticleExtractor})
doc = Nokogiri::HTML.parse(result)
end
end
end
在上述情况下,如果出现 500 内部服务器错误,应用程序将在 Nokogiri::HTML.parse() 上给出错误。我想避免这个问题。如果服务器给出错误,我想继续计算,忽略此页面。
有什么方法可以使用这些工具处理 500 内部服务器错误和 404 未找到页面吗?
亲切的问候, 雨果
最佳答案
# gets the reponse of the link
res = Net::HTTP.get_response(URI.parse(url))
# if it returns a good code
if res.code.to_i >= 200 && res.code.to_i < 400 #good codes will be betweem 200 - 399
# do something with the url
else
# skip the object
next
end
关于ruby-on-rails - 如何使用 Anemone、Boilerpipe 和 Nokigiri 处理 500 内部服务器错误和 404 未找到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18580441/