如何在rails中打开URL?

发布于 2024-09-04 14:21:53 字数 298 浏览 2 评论 0原文

我正在尝试读取某个网站的 html。

尝试 @something = open("http://www.google.com/") 失败,并出现以下错误:

Errno::ENOENT in testController#show

No such file or directory - http://www.google.com/

转至 http://www.google.com/,我显然看到了这个网站。我做错了什么?

谢谢!

I'm trying to read in the html of a certain website.

Trying @something = open("http://www.google.com/") fails with the following error:

Errno::ENOENT in testController#show

No such file or directory - http://www.google.com/

Going to http://www.google.com/, I obviously see the site. What am I doing wrong?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天赋异禀 2024-09-11 14:21:53

您首先需要require 'open-uri'才能open()远程路径。

有关详细信息,请参阅文档

You need to require 'open-uri' first to be able to open() remote paths.

See the docs for more info.

蝶…霜飞 2024-09-11 14:21:53

您应该使用像 Nokogiri 这样的实用程序来解析返回的内容,如下所示:(

来自 Nokogiri 网站首页@ http://nokogiri。 org/)

require 'nokogiri'
require 'open-uri'

# Get a Nokogiri::HTML:Document for the page we’re interested in...

doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))

# Do funky things with it using Nokogiri::XML::Node methods...

# Search for nodes by css
doc.css('h3.r a.l').each do |link|
  puts link.content
end

将打印到屏幕上:

<a href="http://some.link/">Some Link</a>

You should use a utility like Nokogiri to parse the returned content like so:

(From the Nokogiri site front page @ http://nokogiri.org/)

require 'nokogiri'
require 'open-uri'

# Get a Nokogiri::HTML:Document for the page we’re interested in...

doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))

# Do funky things with it using Nokogiri::XML::Node methods...

# Search for nodes by css
doc.css('h3.r a.l').each do |link|
  puts link.content
end

will print to the screen:

<a href="http://some.link/">Some Link</a>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文