以字符串形式检索URL的内容 [英] Retrieve contents of URL as string

查看:67
本文介绍了以字符串形式检索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 }

这篇关于以字符串形式检索URL的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆