首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调整Nokogiri连接的超时

调整Nokogiri连接的超时
EN

Stack Overflow用户
提问于 2013-01-24 18:07:40
回答 1查看 3.3K关注 0票数 2

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

代码语言:javascript
复制
# 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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-24 20:10:29

timeout块只是简单地该代码在不触发异常的情况下在块内执行的最大时间。它不会影响诺基里或OpenURI内部的任何东西。

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

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

调整读取超时

您可以在OpenURI上调整的唯一超时是读取超时。您似乎无法通过此方法更改连接超时:

代码语言:javascript
复制
open(url, :read_timeout => 10)

调整连接超时

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

代码语言:javascript
复制
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

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14498653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档