代码之家  ›  专栏  ›  技术社区  ›  dennismonsewicz

hpricot分析图像alt文本

  •  0
  • dennismonsewicz  · 技术社区  · 14 年前

    我正在尝试使用hpricot从页面上的所有图像中提取alt文本,但无法确定如何执行。

    以前有人做过吗?

    谢谢! 丹尼斯

    1 回复  |  直到 14 年前
        1
  •  2
  •   Doug    14 年前

    这是我第一次用 Hpricot 所以要温柔。我认为这隔离了你询问的数据。

    require 'rubygems'
    require 'hpricot'
    
    page = "<html><body><p>Create a link of an image:<a href=\"default.asp\"><img src=\"smiley.gif\" alt=\"alt_text_1\" width=\"32\" height=\"32\" /></a></p><p>No border around the image, but still a link:<a href=\"default.asp\"><img border=\"0\" src=\"smiley.gif\" alt=\"alt_text_2\" width=\"32\" height=\"32\" /></a></p></body></html>"
    doc = Hpricot(page)
    
    doc.search("//img").each do |img|
        puts img.attributes['alt']
    end
    

    输出如下:

    #=> alt_text_1
    #=> alt_text_2