我正在尝试使用 Hpricot 从页面上的所有图像中提取替代文本,但不知道该怎么做。
有没有人这样做过?
谢谢!丹尼斯
这是我第一次使用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