我需要多次读取网页的内容,并从中提取一些信息,我使用正则表达式。我使用open-uri
阅读网页内容,我编写的代码示例如下:阅读红宝石中的几个URI
require 'open-uri'
def getResults(words)
results = []
words.each do |word|
results.push getAResult(word)
end
results
end
def getAResult(word)
file = open("http://www.somapage.com?option=#{word}")
contents = file.read
file.close
contents.match /some-regex-here/
$1.empty? ? -1 : $1.to_f
end
的问题是,除非我注释掉file.close
线getAResult
总是-1
回报。当我在控制台上试用此代码时,getAResult
立即返回-1
,但ruby进程运行另外两到三秒左右。
如果我删除file.close
线getAResult
返回正确的结果,但现在getResults
是除了第一个一堆-1
秒。我尝试使用curb
gem来阅读页面,但出现类似的问题。
这看起来像是一个与线程相关的问题。但是,我无法想出合理的方法来搜索并找到相应的解决方案。你认为问题是什么?
注意:我尝试阅读的此网页不会如此快速地返回结果。这需要一些时间。
请再次阅读该问题。这不是关于匹配或正则表达式。这是关于我获得网页内容准备和功能返回结果的时间。 – mert