Python lxml筛选子标记之间没有文本的HTML标记

Python lxml筛选子标记之间没有文本的HTML标记,python,lxml,Python,Lxml,我有一些这样的文件 .... <tag1> <tag2>Foo</tag2> <tag3>Bar</tag3> </tag1> <tag1> <tag2>Foo</tag2> <tag3>Bar</tag3> Foo </tag1> <tag1> <ta

我有一些这样的文件

....
  <tag1>
     <tag2>Foo</tag2>
     <tag3>Bar</tag3>
  </tag1>

  <tag1>
     <tag2>Foo</tag2>
     <tag3>Bar</tag3>
     Foo
  </tag1>

  <tag1>
     <tag2>Foo</tag2>     
     Foo
     <tag3>Bar</tag3>
  </tag1>

  <tag1>
     Foo
  </tag1>
 ....
但事实证明getchildren不会返回不在任何标记之间的文本。如何做到这一点?

使用以下标签:

for tag in tag1:
    exists = False
    for child in tag.getchildren():
        exists = exists or not child.tail.strip()
    if not exists:
        tags.append(tag)
根据您所说的“仅具有子项”标记的含义,这相当于:

for tag in tag1:
  children = tag.getchildren()
  no_extra_text = not any(child.tail.strip() for child in children)
  if children and no_extra_text:
    tags.append(tag)
这里有一个更新,包括检查前导文本,并在文本为“无”时删除错误。我想它将始终是一个字符串:

for tag in tag1:
  children = tag.getchildren()
  no_extra_text = not any(child.tail and child.tail.strip() for child in children)
  no_text = tag.text and not tag.text.strip()
  if children and no_extra_text and no_text:
    tags.append(tag)
使用标签的名称:

for tag in tag1:
    exists = False
    for child in tag.getchildren():
        exists = exists or not child.tail.strip()
    if not exists:
        tags.append(tag)
根据您所说的“仅具有子项”标记的含义,这相当于:

for tag in tag1:
  children = tag.getchildren()
  no_extra_text = not any(child.tail.strip() for child in children)
  if children and no_extra_text:
    tags.append(tag)
这里有一个更新,包括检查前导文本,并在文本为“无”时删除错误。我想它将始终是一个字符串:

for tag in tag1:
  children = tag.getchildren()
  no_extra_text = not any(child.tail and child.tail.strip() for child in children)
  no_text = tag.text and not tag.text.strip()
  if children and no_extra_text and no_text:
    tags.append(tag)
你有什么办法

返回所有直接子级。元素按文档顺序返回

所以getchildren返回节点。每个节点都具有以下属性:

, , 和 其他人,请阅读。 对于你所问的问题,答案是谁会给你答案

文本位于该元素的结束标记之后,但在下一个同级元素的开始标记之前。这是一个字符串或值None(如果没有文本)

你有什么办法

返回所有直接子级。元素按文档顺序返回

所以getchildren返回节点。每个节点都具有以下属性:

, , 和 其他人,请阅读。 对于你所问的问题,答案是谁会给你答案

文本位于该元素的结束标记之后,但在下一个同级元素的开始标记之前。这是一个字符串或值None(如果没有文本)


当你说只有子标签时,你的意思是他们仍然必须有子标签吗?那么,会包括吗?不,不应该包括。当你说只有子标签时,你的意思是他们仍然必须有子标签吗?那么,会包括在内吗?不,不应该包括在内。是的,这正是我的意思。谢谢!等等,这能处理这个案子吗?foobar?@PetraBarus-更新来处理这个案子:是的,这正是我的意思。谢谢!等等,这能处理这个案子吗?foobar?@PetraBarus-更新以处理这个案子: