我构建了一个代码,可以在网站上为我投票...
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 answer或Mechanize::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/