以字符串形式检索URL的内容
问题描述:
由于与Hpricot有关的繁琐原因,我需要编写一个传递URL的函数,并以单个字符串返回页面的全部内容.
For tedious reasons to do with Hpricot, I need to write a function that is passed a URL, and returns the whole contents of the page as a single string.
我很近.我知道我需要使用OpenURI,并且它应该看起来像这样:
I'm close. I know I need to use OpenURI, and it should look something like this:
require 'open-uri'
open(url) {
# do something mysterious here to get page_string
}
puts page_string
有人可以建议我需要添加什么吗?
Can anyone suggest what I need to add?
答
open
方法在产生资源时将资源的IO
表示形式传递给您的块.您可以使用 IO#read
方法
The open
method passes an IO
representation of the resource to your block when it yields. You can read from it using the IO#read
method
open([mode [, perm]] [, options]) [{|io| ... }]
open(path) { |io| data = io.read }