2016-12-10 3 views
0

私はElementTreeを使っていくつかのhtmlを処理しています。私はhtmlはXML言語だと思うので、これは大丈夫です。 HTMLでElementTree要素で複数のテキスト部分を表す方法は?

は、テキスト内のタグを持つことができます。

<p> 
This paragraph <em>has some</em> emphasised words. 
</p> 

だから、「P」の要素は、いくつかのテキスト(「この段落 『)、子要素(』 EM」)といくつかのより多くのテキストを(持っています"強調された単語")

しかし、ElementTree要素には文字列であるtext属性があります。子要素はリストにありますが、テキストはすべて1つの文字列にまとめられています。

ElementTreeでこのhtmlをどのように表しますか?出来ますか?

答えて

2

あなたはそれを解析しようとしていますか?

import xml.etree.ElementTree as ET 

def processElem(elem): 
    if elem.text is not None: 
     print elem.text 
    for child in elem: 
     processElem(child) 
     if child.tail is not None: 
      print child.tail 

xml = '''<p> 
This paragraph <em>has some</em> emphasised words. 
</p>''' 

root = ET.fromstring(xml) 
processElem(root) 

ができます:

This paragraph 
has some 
emphasised words. 

それとも、HTMLを修正しようとしていますか?

from xml.etree.ElementTree import Element, SubElement, tostring 
top = Element('p') 
top.text = 'This paragraph ' 
child_with_tail = SubElement(top, 'em') 
child_with_tail.text = 'has some' 
child_with_tail.tail = ' emphasised words.' 
print tostring(top) 

ができます:

<p>This paragraph <em>has some</em> emphasised words.</p> 
+0

ああ、あなたは各埋め込み要素の後のテキストは、次の組み込みの要素まで、埋め込まれた要素の尾に住んでいると言っているので? – fpeelo

+0

はい、正しいです。 https://docs.python.org/2/library/xml.etree.elementtree.html#element-objectsをご覧ください。 –

関連する問題