ruby - 调整 Nokogiri 连接的超时

标签 ruby timeout nokogiri open-uri net-http

为什么 nokogiri 在服务器繁忙时等待几秒 (3-5),而我正在一个接一个地请求页面,但是当这些请求处于循环中时,nokogiri 不会等待并抛出超时消息。 我正在使用超时 block 包装请求,但 nokogiri 根本不等待那个时间。 对此有什么建议的程序吗?

# this is a method from the eng class
def get_page(url,page_type)
 begin
  timeout(10) do
    # Get a Nokogiri::HTML::Document for the page we’re interested in...
    @@doc = Nokogiri::HTML(open(url))
  end
 rescue Timeout::Error
  puts "Time out connection request"
  raise
  end
end

 # this is a snippet from the main app calling eng class
 # receives a hash with urls and goes throgh asking one by one
 def retrieve_in_loop(links)
  (0..links.length).each do |idx|
    url = links[idx]
    puts "Visiting link #{idx} of #{links.length}"
    puts "link: #{url}"
    begin
        @@eng.get_page(url, product)
    rescue Exception => e
        puts "Error getting url: #{idx} #{url}"
        puts "This link will be skeeped. Continuing with next one"
    end
  end
end

最佳答案

timeout block 只是该代码必须在 block 内执行而不触发异常的最长时间。它不会影响 Nokogiri 或 OpenURI 中的任何内容。

您可以将超时设置为一年,但 OpenURI 仍然可以随时超时。

所以您的问题很可能是 OpenURI 本身在连接尝试时超时。 Nokogiri 没有超时;它只是一个解析器。

调整读取超时

您可以在 OpenURI 上调整的唯一超时是读取超时。看来你不能通过这种方法改变连接超时:

open(url, :read_timeout => 10)

调整连接超时

要调整连接超时,您必须直接使用 Net::HTTP:

uri = URI.parse(url)

http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = 10
http.read_timeout = 10

response = http.get(uri.path)

Nokogiri.parse(response.body)

您还可以在此处查看一些其他讨论:

Ruby Net::HTTP time out
Increase timeout for Net::HTTP

关于ruby - 调整 Nokogiri 连接的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14498653/

相关文章:

ruby-on-rails - 开发中的 Rails.cache.fetch 缓存

Ruby 区分数字和字母

javascript - 循环内 sleep /延迟/超时

android - 异步任务 : how to add check on internet connection faults?

android - 仅在有限/固定时间内隐藏进度对话框

ruby - 使用 Ruby 解析 HTML 表,Nokogiri 省略列标题

css - 选择第一个类别之后的所有类别

ruby-on-rails - 为 Rails 寻找一个好的 wiki 平台

ruby-on-rails - RSpec:测试模型是否接收带有特定参数的#create?

ruby-on-rails - 无法加载此类文件 - Nokogiri rails