Ruby/Mechanize 有什么方法可以耗尽 RAM? -> 分配内存失败

标签 ruby variables memory mechanize ram

我构建了一个代码,可以在网站上为我投票...

Ruby 脚本工作得很好,但几分钟后该脚本停止并出现以下错误:link of the screen-shot

所以我检查了 Windows 任务管理器,分配给 ruby​​.exe 的内存在每次循环后都会增长!

这是无罪的和平代码:

class VoteWebsite
        def self.main
        agent = Mechanize.new
        agent.user_agent_alias = 'Windows Mozilla'
    while $stop!=true
        page = agent.get 'http://website.com/vote.php'
        reports_divs = page.search(".//div[@class='Pad1Color2']")
        tds = reports_divs.search("td")
        i = 3;j = 0;ouiboucle=0;voteboucle=0
        while i < tds.length
            result = tds[i].to_s.scan(/<font class="ColorRed"><b>(.*?) :<\/b><\/font>/)
            type = result[0].to_s[2..-3]
            k=i
            case type
            when "Type of vote"
                j= i+1;i += 4
                result2 = tds[j].to_s.scan(/<div id="btn(.*?)">/)           
                id = result2[0].to_s[2..-3]
                monvote=define_vote($vote_type, tds[k].to_s, $vote_auto)
                page2 = agent.get 'http://website.com/AJAX_Vote.php?id='+id+'&vote='+monvote
                voteboucle+=1
                .
                .
                .
            else
                .
                .
                .
            end
        end     
    end
    end
end
VoteWebsite.main

我认为将方法内的所有变量声明为全局变量应该可以解决这个问题,但代码相当大,并且该方法内有很多变量。

那么有没有什么方法(任何 Ruby 指令)可以在每个循环结束时耗尽所有这些变量?

最佳答案

问题实际上来自 Mechanize 的历史 see this answerMechanize::History.clear方法,甚至只需设置 Mechanize::History.max_size属性为合理的值。

#!/usr/bin/env ruby

require 'mechanize'

class GetContent
    def initialize url
        agent = Mechanize.new
    agent.user_agent_alias = 'Windows Mozilla'
    agent.history.max_size=0
    while true
            page = agent.get url
        end
    end
end

myPage = GetContent.new('http://www.nypost.com/')

希望对你有帮助!

关于Ruby/Mechanize 有什么方法可以耗尽 RAM? -> 分配内存失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7162939/

相关文章:

ruby-on-rails - render_views 助手没有按预期工作

Ruby 正则表达式,只有一次捕获(非常简单!)

node.js - 我是否应该在不同函数调用中使用不同赋值的变量使用 const,但不会在同一调用中重新赋值

java - 在JTable中显示内存消耗较高的ResultSet

c - 无明显原因增加++ 值的无符号整型变量

c++ - 如果关闭 fun() 后所有内存都被释放,那么输出是如何打印的

模块中的 Ruby 类需要访问包含类命名空间

javascript - 如何使用 Dino 和 Sinatra 显示传感器输出?

c# - 变量应该显式还是隐式类型化?

java - 为什么 `synchronized` 对于变量来说是非法的?