我正在尝试遍历一个html字符串并将文本内容连接起来,并使用一个字符串合并器,它会随所遇到的html标记的类型而变化。
示例html:html_str='<td><p>This is how<br>we<br><strong>par<sup>s</sup>e</strong><br>our string</p> together</td>'
我编写了一个名为smart_itertext()的助手函数,通过方法e.iter()遍历html元素e。对于e.iter()中的每个e.iter(),它检查标记,然后追加.text或.tail内容。
我的挑战是让尾巴的文字出现在正确的地方。当我通过标记迭代时,我到达了<p>,这似乎是我访问拖尾文本‘一起’的唯一机会。
预期结果:
>>>smart_itertext(lxml.html.fromstring(html_str))
'This is how::we::parse::our string::together'实际结果:
>>>smart_itertext(lxml.html.fromstring(html_str))
'This is how:: together::::we::parse::::our string'这是我的职责:
def smart_itertext(tree, cross_joiner='::'):
empty_join= ['strong','b','em','i','small','marked','deleted',
'ins', 'sub','sup']
cross_join = ['td','tr','br','p']
output=''
for element in tree.iter():
if element.tag in empty_join:
if element.text:
output += element.text
if element.tail:
output += element.tail
elif element.tag in cross_join:
if element.text:
output += cross_joiner + element.text
else:
output += cross_joiner
if element.tail:
output += cross_joiner + element.tail
else:
print ('unknown tag in smart_itertext:',element.tag)
return output做这件事的正确方法是什么?
发布于 2015-11-23 16:55:30
答案是使用xpath,它允许您按照文档顺序构建一个内容文本列表,其中包含属性is_tail和is_text,以及getparent()方法。
来自lxml.html教程:
注意,XPath返回的字符串结果是一个特殊的“智能”对象,它知道它的起源。您可以问它是从哪里来的,就像使用元素一样:TEXT = build_text_list(html) >>> print(TEXT)TEXT >>> >>> = texts.getparent() >>> print(parent.tag) body >>> print(texts1)尾部>>> print(texts1.getparent().tag) br 您还可以找到它是普通的文本内容还是尾文本: 打印(texts.is_text)真>>>打印(texts1.is_text)假>>>打印(texts1.is_tail)真
https://stackoverflow.com/questions/33742513
复制相似问题