我想要計算某個頁面中幾個html標籤的出現次數。我可以用經典的方式做到這一點,但我試圖用Ruby的方式來做到這一點。Couting與Ruby風格的html標籤(注入,塊,每個...)
這是我做的,但不是增加了各部分的計數,它創建與列表中的元素的字符串:
tags = [ '<img>', '<script>', '<applet>', '<video>', '<audio>' ]
weight = tags.each { |tag| web.to_s.scan(/#{tag}/).length }.inject(:+)
任何提示嗎?
編輯:
def browse startpage, depth, block
if depth > 0
begin
web = open(startpage).read
block.call startpage, web
rescue
return
end
links = URI.extract(web)
links.each { |link| browse link, depth-1, block }
end
end
browse("https://www.youtube.com/", 2, lambda { |page_name, web|
tags = [ '<img>', '<script>', '<applet>', '<video>', '<audio>' ]
web.force_encoding 'utf-8'
parsed_string = Nokogiri::HTML(web)
weight = tags.each_with_object(Hash.new(0)) do |tag, hash|
occurrences = parsed_string.xpath("//#{tag.gsub(/[<>]/, '')}").length
hash[tag] = occurrences
end
puts "Page weight for #{web.base_uri} = #{weight}"
})
只是更換''each' map' – 2014-11-06 12:36:44
Revemo救援塊與返回一起,這使調試不可能。 – daremkd 2014-11-06 13:10:11