lxml:我无法删除 span 标签和里面的文本

lxml: I can't remove a span tag and the text inside

我有一个 html 文件,其中包含一些像这样的 div(简化了很多):

<div num="1" class="class1">
  <div class="class1-text">
    <span class="class2">
      <span class="class3"> some chinese text </span>
      some english text
    </span>
  </div>
</div>

我试图通过删除包含 lxml 的跨度节点来删除所有中文文本:

parser = et.XMLParser(remove_blank_text=True, recover=True)
documentXml=et.parse(html_FileName, parser)
for class1Node in documentXml.xpath('//div[@class="class1-text"]'):
    chineseNode=class1Node.xpath('.//span[@class="class3"]')
    chineseNode.getparent().remove(chineseNode)

但我不是从 xpath 中获取 span class3 节点,而是获取 span class2,因此我最终删除了所有内容(甚至是英文文本)。

如果我不使用 lxml 进行解析,则会出现解析错误(可能是汉字问题或错误 html)。

您可以尝试使用 strip_elements() 函数,例如:

from lxml import etree as et

parser = et.XMLParser(remove_blank_text=True, recover=True)
documentXml=et.parse(html_FileName, parser)
for class1Node in documentXml.xpath('//div[@class="class1-text"]'):
    chineseNode=class1Node.xpath('.//span[@class="class3"]')
    et.strip_elements(chineseNode[0].getparent(), 'span', with_tail=False)

print(et.tostring(documentXml))

它产生:

b'<div num="1" class="class1"><div class="class1-text"><span class="class2">\n      some english text\n    </span></div></div>'

您应该能够将 xpath 选择器简化为:

for chineseNode in documentXml.xpath("//div[@class='class1-text']//span[@class='class3']"):
    chineseNode.getparent().remove(chineseNode)