我需要使用python的lxml基于属性的内容完全删除元素.例:
import lxml.etree as et
xml="""
<groceries>
<fruit state="rotten">apple</fruit>
<fruit state="fresh">pear</fruit>
<fruit state="fresh">starfruit</fruit>
<fruit state="rotten">mango</fruit>
<fruit state="fresh">peach</fruit>
</groceries>
"""
tree=et.fromstring(xml)
for bad in tree.xpath("//fruit[@state=\'rotten\']"):
#remove this element from the tree
print et.tostring(tree, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)
我想要打印:
<groceries>
<fruit state="fresh">pear</fruit>
<fruit state="fresh">starfruit</fruit>
<fruit state="fresh">peach</fruit>
</groceries>
Run Code Online (Sandbox Code Playgroud)
有没有办法在不存储临时变量并手动打印的情况下执行此操作,如下所示:
newxml="<groceries>\n"
for elt in tree.xpath('//fruit[@state=\'fresh\']'):
newxml+=et.tostring(elt)
newxml+="</groceries>"
Run Code Online (Sandbox Code Playgroud) 我有一个html文件,我想用空格替换空段落.
mystring = "This <p></p><p>is a test</p><p></p><p></p>"
result = mystring.sub("<p></p>" , " ")
Run Code Online (Sandbox Code Playgroud)
这不起作用.
我正在使用 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"
Run Code Online (Sandbox Code Playgroud)
如果可能的话,替换实际上应该在这个循环内完成,因为无论如何我们都需要循环,并且在其中包含此步骤可能是最有效的方法。
SO 上有一个类似的问题/答案,但它无助于解决问题: How can one Replace an element with text in lxml?