Ruby 提取 HTML 文档中的链接和图片

2015-03-07 0 210
Ruby 提取 HTML 文档中的链接和图片
require 'rexml/document'
require 'rexml/streamlistener'
require 'set'

class LinkGrabber
  include REXML::StreamListener
  attr_reader :links

 def initialize(interesting_tags = {'a' => %w{href}, 'img' => %w{src}}.freeze)
    @tags = interesting_tags
    @links = Set.new
  end

  def tag_start(name, attrs)
    @tags[name].each do |uri_attr|
      @links << attrs[uri_attr] if attrs[uri_attr]
    end if @tags[name]
  end

  def parse(text)
    REXML::Document.parse_stream(text, self)
  end
end


text = %{"test
<a href="http://www.example.com/" rel="external nofollow" >http://www.example.com/</a>, http://www.example.com/blog/. Email me at <a
href="mailto:bob@example.com" rel="external nofollow" >b@e.com</a>.}

grabber = LinkGrabber.new
grabber.parse(text)
p grabber.links

遇见资源网 ruby Ruby 提取 HTML 文档中的链接和图片 http://www.ox520.com/16274.html

上一篇: Stream的Ruby实现
下一篇: rot13 加密算法
常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务