2010-11-15 4 views
1

J'ai quelques fichier html:Comment puis-je analyser html en utilisant lxml, python

<html> 
<body> 
    <span class="text">One</span>some text1</br> 
    <span class="cyrillic">Мир</span>some text2</br> 
</body> 
</html> 

Comment puis-je obtenir "certains text1" et "certains texte2" à l'aide lxml avec python?

+0

Voici le tutoriel: http://codespeak.net/lxml/tutorial.html Tout spécifique que vous ne comprenez pas? – Wolph

+0

Ce lien de tutoriel est défunt. S'il vous plaît retirer. – ely

Répondre

5
import lxml.html 

doc = lxml.html.document_fromstring("""<html> 
<body> 
    <span class="text">One</span>some text1</br> 
    <span class="cyrillic">Мир</span>some text2</br> 
</body> 
</html> 
""") 

txt1 = doc.xpath('/html/body/span[@class="text"]/following-sibling::text()[1]') 
txt2 = doc.xpath('/html/body/span[@class="cyrillic"]/following-sibling::text()[1]') 
3

J'utilise lxml pour l'analyse XML, mais j'utilise BeautifulSoup pour HTML. Voici une visite très rapide/brève, se terminant par une solution à votre question. J'espère que cela aide.

Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from BeautifulSoup import BeautifulSoup as soup 
>>> stream = open('bs.html', 'r') 
>>> doc = soup(stream.read()) 
>>> doc.body.span 
<span class="text">One</span> 
>>> doc.body.span.nextSibling 
u'some text1' 
>>> x = doc.findAll('span') 
>>> for i in x: 
...  print unicode(i) 
... 
<span class="text">One</span> 
<span class="cyrillic">Мир</span> 
>>> x = doc('span') 
>>> type(x) 
<class 'BeautifulSoup.ResultSet'> 
>>> for i in x: 
...  print unicode(i) 
... 
<span class="text">One</span> 
<span class="cyrillic">Мир</span> 
>>> for i in x: 
...  print i.nextSibling 
... 
some text1 
some text2 
>>> 
Questions connexes