调整Nokogiri连接的超时
为什么nokogiri在服务器繁忙时等待几秒钟(3-5)并且我一个接一个地请求页面,但是当这些请求处于循环中时,nokogiri不会等待并抛出超时消息。 我正在使用超时块包装请求,但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
块只是该代码必须在块内执行而不触发exception的最长时间 。 它不会影响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超时
增加Net :: HTTP的超时
- 如何在具有名为“attribute”的列的数据库上使用ActiveRecord? (DangerousAttributeError)
- Rails belongs_to关联,在集合的一部分时无法访问所有者的属性?
- 如何使用socksify gem(代理)抓取网站
- 证书续订后,Ruby Net :: HTTP响应OpenSSL :: SSL :: SSLError“证书validation失败”
- 如何使用Ruby在文本文件中搜索完全匹配的字符串?
- 在RoR中,如何从“无法打开TCP连接…(一般SOCKS服务器故障)”错误中恢复?
- 使用Net :: HTTP的块forms的HTTPS请求 – 是否可能?
- 使用Net / http发布JSON格式的Ruby数据
- 使用ruby Net:HTTP API将文件上载到远程apache服务器失败,发生409冲突
- Ruby,Tor和Net :: HTTP :: Proxy
- 如何在ruby中设置自定义用户代理