2010-12-03 8 views
0

Maintenant que mon html:Comment obtenir des éléments incorporés dans du texte avec nokogiri?

<div class="cardtextbox"><i>(<img src="/Handlers/Image.ashx?size=small&amp;name=BR&amp;type=symbol" alt="Black or Red" align="absbottom" /> can be paid with either <img src="/Handlers/Image.ashx?size=small&amp;name=B&amp;type=symbol" alt="Black" align="absbottom" /> or <img src="/Handlers/Image.ashx?size=small&amp;name=R&amp;type=symbol" alt="Red" align="absbottom" />.)</i></div><div class="cardtextbox"><img src="/Handlers/Image.ashx?size=small&amp;name=3&amp;type=symbol" alt="3" align="absbottom" /><img src="/Handlers/Image.ashx?size=small&amp;name=B&amp;type=symbol" alt="Black" align="absbottom" />, Discard a card: Target creature gets -2/-2 until end of turn.</div><div class="cardtextbox"><img src="/Handlers/Image.ashx?size=small&amp;name=3&amp;type=symbol" alt="3" align="absbottom" /><img src="/Handlers/Image.ashx?size=small&amp;name=R&amp;type=symbol" alt="Red" align="absbottom" />: Put a 2/1 red Goblin creature token with haste onto the battlefield. Exile it at the beginning of the next end step.</div></div> 

Et ce que je voudrais obtenir:

[ 
["(B/R can be paid with either B or R.)"], 
["3 B, Discard a card", "Target creature gets -2/-2 until end of turn"], 
["3 R",     "Put a 2/1 red Goblin creature token with haste onto the battlefield. Exile it at the beginning of the next end step."] 
] 

Mapping de Red => R se fait via colorhash. Le rouge provient de la balise img, alt.

Répondre

0

Je ne suis pas sûr de ce qu'est colorhash, ou comment c'est pertinent à cette question, mais voici quelque chose qui devrait vous rapprocher. Si vous voulez vraiment un tableau imbriqué de réponses, vous devrez définir une fonction récursive pour traiter un nœud et déterminer vous-même si un nœud est une feuille ou non.

require 'nokogiri' 
colorhash = { 
    'Red'   => 'R', 
    'Black'  => 'B', 
    'Black or Red' => 'B/R' 
} 

h = Nokogiri::HTML html_from_question 

# Replace all images with alt text, possibly transformed 
h.xpath('//img[@alt]').each{ |i| i.swap(colorhash[i['alt']] || i['alt']) } 

require 'pp' 
pp h.css('.cardtextbox').map(&:text) 

#=> ["(B/R can be paid with either B or R.)", 
#=> "3B, Discard a card: Target creature gets -2/-2 until end of turn.", 
#=> "3R: Put a 2/1 red Goblin creature token with haste onto the battlefield. Exile it at the beginning of the next end step."] 
Questions connexes