正如 llasram 所说,任何不在text
属性中的文本都将在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]
我没有用普通的旧 stdlib ElementTree 测试过这个,但它也应该适用。(当我看到 Shane Holloway 的 lxml 特定解决方案时,我才想到这一点)我只是更喜欢 LXML,因为它对 HTML 的 ideosyncracies 有更好的支持,而且我通常已经安装了它lxml.html.clean