我如何处理rest-client 500错误响应并不断在我的循环中抓取?

问题描述 投票:0回答:1

我需要从该网站上抓取1万个URL,其中一些URL不再可用(我认为...这是一个错误,不返回我要查找的JSON,因此rest-client在我的网站中返回500 Internal Server error程序)

错误语法:`exception_with_response':500内部服务器错误(RestClient :: InternalServerError)

要遍历URL,我使用的是range (1..30).each do |id|。我将URL与该范围的当前迭代连接在一起。

response = RestClient.get(url+id)

问题是有时我存储在响应变量中的URL不存在和/或网页返回了一些错误。如何保护我的代码,以便我可以通过这个有问题的URL并保持报废?

这是我当前的代码(我将循环的每个代码都放在了begin / rescue块中,但是我不知道如何编写代码来执行此操作:]]

require 'nokogiri'
require 'csv'
require 'rest-client'
require 'json'

link = "https://webfec.org.br/Utils/GetCentrobyId?cod="
CSV.open('data2.csv', 'ab') do |csv|
    csv << ['Name', 'Street', 'Info', 'E-mail', 'Site']
    (1..30).each do |id|
        begin
            response = RestClient.get(link+id.to_s)
            json = JSON.parse(response)
            html = json["Data"]
            doc = Nokogiri::HTML.parse(html)

            name = doc.xpath("/html/body/table/tbody/tr[1]").text
            street = doc.xpath("/html/body/table/tbody/tr[2]").text.gsub(Regexp.union(REMOVER), " ")
            info = doc.xpath("/html/body/table/tbody/tr[3]").text.gsub(Regexp.union(REMOVER), " ")
            email = doc.xpath("/html/body/table/tbody/tr[4]").text.gsub(Regexp.union(REMOVER), " ")
            site = doc.xpath("/html/body/table/tbody/tr[5]").text.gsub(Regexp.union(REMOVER), " ")

            csv << [name, street, info, email, site]
        rescue

        end
    end
end

[您可以看到我将所有内容放入begin块中的循环中,并且在末尾有rescue块,但是我对如何处理此类事情感到迷茫。

我需要从此网站上抓取1万个URL,其中一些URL不再可用(我认为...这是一个错误,不返回我要查找的JSON,所以rest-client返回500 Internal Server .. 。

ruby rest-client
1个回答
1
投票

您应该挽救例外,例如:

© www.soinside.com 2019 - 2024. All rights reserved.