【问题标题】:Ruby Mechanize Stops Working while in Each Do LoopRuby Mechanize 在每个 Do 循环中停止工作
【发布时间】:2014-08-19 08:50:37
【问题描述】:

我正在使用机械化 Ruby 脚本来循环遍历制表符分隔文件中的大约 1,000 条记录。在我达到大约 300 条记录之前,一切都按预期工作。

一旦我获得大约 300 条记录,我的脚本就会在每次尝试时不断调用救援并最终停止工作。我以为是因为我没有正确设置max_history,但这似乎没有什么影响。

这是我开始收到的错误消息:

getaddrinfo: nodename nor servname provided, or not known

关于我在这里可能做错的任何想法?

require 'mechanize' 
result_counter = 0
used_file = File.open(ARGV[0])
total_rows = used_file.readlines.size

mechanize = Mechanize.new { |agent|
  agent.open_timeout   = 10
  agent.read_timeout   = 10
  agent.max_history = 0
}

File.open(ARGV[0]).each do |line|
  item = line.split("\t").map {|item| item.strip}
  website = item[16]
  name = item[11]

  if website
    begin
      tries ||= 3
      page = mechanize.get(website)

      primary1 = page.link_with(text: 'text')
      secondary1 = page.link_with(text: 'other_text')
      contains_primary = true
      contains_secondary = true

      unless contains_primary || contains_secondary
        1.times do |count|
          result_counter+=1
          STDERR.puts "Generate (#{result_counter}/#{total_rows}) #{name} - No"
        end
      end

      for i in [primary1]
        if i
          page_to_visit = i.click
          page_found = page_to_visit.uri
          1.times do |count|
            result_counter+=1
            STDERR.puts "Generate (#{result_counter}/#{total_rows}) #{name}"
          end
          break
        end
      end
    rescue Timeout::Error
      STDERR.puts "Generate (#{result_counter}/#{total_rows}) #{name} - Timeout"
    rescue => e
      STDERR.puts e.message
      STDERR.puts "Generate (#{result_counter}/#{total_rows}) #{name} - Rescue"
    end
  end
end

【问题讨论】:

  • 我正在重新运行日志,并会立即用错误更新问题,谢谢!
  • 抱歉耽搁了!我收到的错误消息是getaddrinfo: nodename nor servname provided, or not known
  • 我认为这可能是这里的解决方案:stackoverflow.com/questions/13186289/…
  • 这可能是网络问题。请检查您的互联网连接,然后重试。

标签: ruby mechanize mechanize-ruby


【解决方案1】:

您收到此错误是因为您在使用后没有关闭连接。

这应该可以解决您的问题:

mechanize = Mechanize.new { |agent|
  agent.open_timeout = 10
  agent.read_timeout = 10
  agent.max_history  = 0
  agent.keep_alive   = false
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多