相关疑难解决方法(0)

如何删除lxml中的元素

我需要使用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)

python xml lxml

79
推荐指数
4
解决办法
5万
查看次数

如何使用python sub删除<p> </ p>

我有一个html文件,我想用空格替换空段落.

mystring = "This <p></p><p>is a test</p><p></p><p></p>"
result = mystring.sub("<p></p>" , "&nbsp;")
Run Code Online (Sandbox Code Playgroud)

这不起作用.

html python string

3
推荐指数
2
解决办法
2240
查看次数

如何用 lxml iterwalk 循环内的文本替换 HTML 标签

我正在使用 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?

html python lxml replace html-parsing

2
推荐指数
1
解决办法
3176
查看次数

标签 统计

python ×3

html ×2

lxml ×2

html-parsing ×1

replace ×1

string ×1

xml ×1