text
llasramが言ったように、属性にないテキストはすべてtail
子ノードの属性になります。
例として、ノード内のすべてのテキストチャンク(最初およびそれ以外)を抽出する最も簡単な方法は次のとおりです。
html = '<div>text1<span>childtext1</span>text2<span>childtext2</span>text3</div>'
import lxml.html # ...or lxml.etree as appropriate
div = lxml.html.fromstring(html)
texts = [div.text] + [child.tail for child in div]
# Result: texts == ['text1', 'text2', 'text3']
# ...and you are guaranteed that div[x].tail == texts[x+1]
# (which can be useful if you need to access or modify the DOM)
空の文字列が含まれる可能性を防ぐためにその関係を犠牲にしたい場合はtexts
、代わりにこれを使用できます。
texts = [div.text] + [child.tail for child in div if child.tail]
私はこれを単純な古いstdlibElementTreeでテストしていませんが、それでも機能するはずです。(Shane Hollowayのlxml固有のソリューションを見たときに初めて発生したこと)HTMLのイデオシンクロシーのサポートが向上し、通常はLXMLがすでにインストールされているため、LXMLの方が好きです。lxml.html.clean