1

我正在尝试解析图像 URL 列表并在实际提交下载之前获取一些基本信息。

  1. 图像在那里(用 response.code 解决?)
  2. 我已经有图片了吗(想查看类型和大小?)

我的脚本每天都会检查一个大列表(大约 1300 行),每行有 30-40 个图像 URL。我的@photo_urls 变量允许我跟踪我已经下载的内容。我真的希望以后能够将其用作哈希(而不是我的示例代码中的数组),以便稍后进行交互并进行实际下载。

现在我的问题(除了是一个 Ruby 新手)是Net::HTTP::Pipeline只接受一组 Net::HTTPRequest 对象。net-http-pipeline 的文档表明响应对象将以与进入的相应请求对象相同的顺序返回。问题是除了该顺序之外,我无法将请求与响应相关联。但是,我不知道如何获得块内的相对序数位置。我假设我可以只有一个计数器变量,但我将如何按序数位置访问散列?

          Net::HTTP.start uri.host do |http|
            # Init HTTP requests hash
            requests = {}
            photo_urls.each do |photo_url|          
              # make sure we don't process the same image again.
              hashed = Digest::SHA1.hexdigest(photo_url)         
              next if @photo_urls.include? hashed
              @photo_urls << hashed
              # change user agent and store in hash
              my_uri = URI.parse(photo_url)
              request = Net::HTTP::Head.new(my_uri.path)
              request.initialize_http_header({"User-Agent" => "My Downloader"})
              requests[hashed] = request
            end
            # process requests (send array of values - ie. requests) in a pipeline.
            http.pipeline requests.values do |response|
              if response.code=="200"
                  # anyway to reference the hash here so I can decide whether
                  # I want to do anything later?
              end
            end                
          end

最后,如果有更简单的方法,请随时提供任何建议。

谢谢!

4

1 回答 1

1

使请求成为数组而不是哈希,并在响应进入时弹出请求:

Net::HTTP.start uri.host do |http|
  # Init HTTP requests array
  requests = []
  photo_urls.each do |photo_url|          
    # make sure we don't process the same image again.
    hashed = Digest::SHA1.hexdigest(photo_url)         
    next if @photo_urls.include? hashed
    @photo_urls << hashed

    # change user agent and store in hash
    my_uri = URI.parse(photo_url)
    request = Net::HTTP::Head.new(my_uri.path)
    request.initialize_http_header({"User-Agent" => "My Downloader"})
    requests << request
  end

  # process requests (send array of values - ie. requests) in a pipeline.
  http.pipeline requests.dup do |response|
    request = requests.shift

    if response.code=="200"
      # Do whatever checking with request
    end
  end                
end
于 2013-07-27T03:15:43.230 回答