需要开发一个接口程序,外部程序提供了一个URL的接口,即访问一个URL,最终会得到相应的执行结果。
例如,
访问http://aaa.com?a='ccc'
则会得到一个页面。
在Rails中,会需要得到这个页面内的内容,再进行相关处理。
请问在Rails中有没有提供类似的方法。
[code="ruby"] require 'open-uri'
doc = open("http://qwantz.com/") { |f| Hpricot(f) }[/code]
简单讲,
最基本要求应该看[url=http://www.ruby-doc.org/stdlib/libdoc/open-uri/rdoc/]open-uri[/url]
会用类似代码
[code="ruby"] open("http://www.ruby-lang.org/en") {|f|
f.each_line {|line| p line}
p f.base_uri #
p f.content_type # "text/html"
p f.charset # "iso-8859-1"
p f.content_encoding # []
p f.last_modified # Thu Dec 05 02:45:02 UTC 2002
}[/code]
可是你扒数据通常会用到,页面解析,那么Rails最常用就是
[url=http://wiki.github.com/why/hpricot]hpricot[/url]
用法大致如下:
[code="ruby"]require 'rubygems'
require 'hpricot'
document = <<END
END
doc = Hpricot.parse(document)
(doc/'li').each do |item|
puts item.inner_html
end[/code]
就可以直接给出first item 跟 second item。
最后,我怀疑的是,你的外部程序接口
如果,那个也是你可以编程的一部,那你就应该,写成web service,这也就不用费劲解析了
大致这些,希望有帮助
其实除了webservice
都是使用ruby的库来访问外部网页