代码之家  ›  专栏  ›  技术社区  ›  Yuval Karmi

如何在rails中打开URL?

  •  2
  • Yuval Karmi  · 技术社区  · 15 年前

    我正在尝试阅读某个网站的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/

    谢谢!

    2 回复  |  直到 15 年前
        1
  •  6
  •   Robert Speicher    15 年前

    require 'open-uri' 首先能够 open()

    看到了吗 the docs 更多信息。

        2
  •  2
  •   Patrick Klingemann    15 年前

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

    (来自 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
    

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