以字符串形式检索 URL 的内容
由于与 Hpricot 相关的繁琐原因,我需要编写一个传递 URL 的函数,并将页面的全部内容作为单个字符串返回。
我很接近。我知道我需要使用 OpenURI,它应该看起来像这样:
require 'open-uri'
open(url) {
# do something mysterious here to get page_string
}
puts page_string
任何人都可以建议我需要添加什么吗?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以在没有 OpenURI 的情况下执行相同的操作:
或者更简洁地说:
You can do the same without OpenURI:
Or, more succinctly:
open
方法在产生时将资源的IO
表示形式传递给您的块。您可以使用IO#read
方法The
open
method passes anIO
representation of the resource to your block when it yields. You can read from it using theIO#read
method另请参阅 IO 类 的文档
See also the documentation of IO class
我也很困惑该使用什么来获得更好的性能和更快的结果。我对两者进行了基准测试,以使其更清楚:
其结果是:
我想说这取决于您的要求是什么以及您想要如何处理。
I was also very confused what to use for better performance and speedy results. I ran a benchmark for both to make it more clear:
Its result is:
I'd like to say that it depends on what your requirement is and how you want to process.
为了使代码更清晰一些,OpenURI
open
方法将返回块返回的值,因此您可以将open
的返回值分配给您的变量。例如:To make code a little clearer, the OpenURI
open
method will return the value returned by the block, so you can assignopen
's return value to your variable. For example:从 Ruby 3.0 开始,通过
Kernel#open
调用URI.open
已被删除,因此请直接调用URI.open
:Starting with Ruby 3.0, calling
URI.open
viaKernel#open
has been removed, so instead callURI.open
directly:请尝试以下方法:
Try the following instead: