获取.text_content()。使用lxml.html 的工作示例:
from lxml.html import fromstring
data = """
<description>
the thing <b>stuff</b> is very important for various reasons, notably <b>other things</b>.
</description>
"""
tree = fromstring(data)
print(tree.xpath("//description")[0].text_content().strip())
打印:
the thing stuff is very important for various reasons, notably other things.
我忘了指定一件事,抱歉。我理想的解析版本将包含一个小节列表:[normal("the thing")、bold("stuff")、normal("....")],lxml.html 库有可能吗?
假设描述中只有文本节点和b 元素:
for item in tree.xpath("//description/*|//description/text()"):
print([item.strip(), 'normal'] if isinstance(item, basestring) else [item.text, 'bold'])
打印:
['the thing', 'normal']
['stuff', 'bold']
['is very important for various reasons, notably', 'normal']
['other things', 'bold']
['.', 'normal']