【问题标题】:Writing a Simple Ruby Script w/ Open URI使用 Open URI 编写简单的 Ruby 脚本
【发布时间】:2011-08-12 07:09:45
【问题描述】:

我正在使用 Ruby 构建一个简单的新闻聚合器。我对这门语言完全陌生,我刚刚发现了如何使用 open uri 函数。

现在,我的问题是如何解析 html 页面。 Ruby 中是否有内置解析器。

顺便说一句,我不使用 Rails,我希望它非常简单

提前致谢!

【问题讨论】:

    标签: ruby screen-scraping nokogiri


    【解决方案1】:

    要解析 HTML,我建议 Nokogiri。特点:

    • XPath 支持文档搜索
    • 文档搜索的 CSS3 选择器支持
    • XML/HTML 构建器

    有一个关于screen scraping with Nokogiri 的精彩截屏视频。

    【讨论】:

      【解决方案2】:

      简单的答案是肯定的,有一个解析器。在不知道您要从 html 中提取什么的情况下,我无法具体回答您的问题,但我在下面提供了一些源代码。如果您能够阅读 ruby​​ 代码,那么它就很容易解释了。

      require 'open-uri'
      require 'pp'
      open('http://ruby-lang.org') do |f|
      puts "URI: #{f.base_uri}"
      puts "Content-type: #{f.content_type}, charset: #{f.charset}"
      puts "Encoding: #{f.content_encoding}"
      puts "Last modified: #{f.last_modified}"
      puts "Status: #{f.status.inspect}"
      pp f.meta
      puts "----"
      3.times {|i| puts "#{i}: #{f.gets}" }
      end
      

      产生:

      URI: http://www.ruby-lang.org/en/
      Content-type: text/html, charset: utf-8
      Encoding: []
      Last modified:
      Status: ["200", "OK"]
      {"date"=>"Mon, 15 Nov 2010 17:54:07 GMT",
      "server"=>
      "Apache/2.2.3 (Debian) DAV/2 SVN/1.4.2 mod_ruby/1.2.6 Ruby/1.8.5(2006-08-25)",
      "transfer-encoding"=>"chunked",
      "content-type"=>"text/html;charset=utf-8"}
      ----
      0: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      1: "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
      2: <html xmlns="http://www.w3.org/1999/xhtml">
      

      这是另一个链接,展示了如何使用 open-uri 的示例:http://juretta.com/log/2006/08/13/ruby_net_http_and_open-uri/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-10
        • 1970-01-01
        • 2010-09-15
        • 1970-01-01
        • 1970-01-01
        • 2019-01-08
        • 1970-01-01
        相关资源
        最近更新 更多