我正在使用 lxml iterwalk 遍历 HTML 树,我想替换所有 <br>
里面的标签 <pre></pre>
换行符。这就是我到目前为止所拥有的:
root = lxml.html.fromstring(text)
for action, el in etree.iterwalk(root):
if el.tag == 'pre':
for br in el.xpath('br'):
# replace this <br> tag with "\n"
如果可能的话,替换应该真的在这个循环内完成,因为无论如何我们都需要循环,并且在其中包括这个步骤可能是最有效的方法。
SO上有一个类似的问题/答案,但没有帮助解决问题: How can one replace an element with text in lxml?
最佳答案
drop_tree()
方法正是您所需要的:
.drop_tree():
Drops the element and all its children. Unlike el.getparent().remove(el) this does not remove the tail text; with drop_tree the tail text is merged with the previous element.
在 pre
中找到所有 br
元素,将 tail
设置为 \n
并删除该元素:
from lxml import etree
import lxml.html
text = """
<div>
<pre>
<br>
test
<br>
</pre>
<br>
</div>
"""
root = lxml.html.fromstring(text)
for action, el in etree.iterwalk(root):
if el.tag == 'pre':
for br in el.xpath('br'):
br.tail = '\n' + br.tail
br.drop_tree()
print etree.tostring(root)
打印:
<div>
<pre>
test
</pre>
<br/>
</div>
关于python - 如何在 lxml iterwalk 循环中用文本替换 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24121362/