2010-09-23 15 views
2

Comment puis-je itérer sur toutes les variables ayant un attribut spécifique avec une valeur spécifique? Par exemple, disons que nous avons besoin de data1, data2 etc ... seulement.Trouver tous les points ayant une valeur d'attribut spécifique

<html> 
    <body> 
     <invalid html here/> 
     <dont care> ... </dont care> 
     <invalid html here too/> 
     <interesting attrib1="naah, it is not this"> ... </interesting tag> 
     <interesting attrib1="yes, this is what we want"> 
      <group> 
       <line> 
        data 
       </line> 
      </group> 
      <group> 
       <line> 
        data1 
       <line> 
      </group> 
      <group> 
       <line> 
        data2 
       <line> 
      </group> 
     </interesting> 
    </body> 
</html> 

J'ai essayé BeautifulSoup mais il ne peut pas analyser le fichier. L'analyseur de lxml, cependant, semble fonctionner:

broken_html = get_sanitized_data(SITE) 

parser = etree.HTMLParser() 
tree = etree.parse(StringIO(broken_html), parser) 

result = etree.tostring(tree.getroot(), pretty_print=True, method="html") 

print(result) 

Je ne suis pas au courant de son API, et je ne pouvais pas comprendre comment utiliser soit getIterator ou XPath.

+0

Avez-vous essayé de changer le type MIME en XML? certains parseurs sont difficiles ... – JKirchartz

+2

Avec lxml utilisant xpath semble être assez facile, donner une chance aux docs :) http://codespeak.net/lxml/xpathxslt.html –

Répondre

3

Voici une façon, en utilisant lxml et le XPath'descendant::*[@attrib1="yes, this is what we want"]'. Le XPath dit à lxml de regarder tous les descendants du nœud actuel et de renvoyer ceux avec un attribut attrib1 égal à "yes, this is what we want".

import lxml.html as lh 
import cStringIO 

content=''' 
<html> 
    <body> 
     <invalid html here/> 
     <dont care> ... </dont care> 
     <invalid html here too/> 
     <interesting attrib1="naah, it is not this"> ... </interesting tag> 
     <interesting attrib1="yes, this is what we want"> 
      <group> 
       <line> 
        data 
       </line> 
      </group> 
      <group> 
       <line> 
        data1 
       <line> 
      </group> 
      <group> 
       <line> 
        data2 
       <line> 
      </group> 
     </interesting> 
    </body> 
</html> 
''' 
doc=lh.parse(cStringIO.StringIO(content)) 
tags=doc.xpath('descendant::*[@attrib1="yes, this is what we want"]') 
print(tags) 
# [<Element interesting at b767e14c>] 
for tag in tags: 
    print(lh.tostring(tag)) 
# <interesting attrib1="yes, this is what we want"><group><line> 
#      data 
#     </line></group><group><line> 
#      data1 
#     <line></line></line></group><group><line> 
#      data2 
#     <line></line></line></group></interesting> 
+0

Merci, vous avez sauvé ma journée! –