确定元素的直接子元素是否为某些标记

时间:2011-11-20 20:10:25

标签: python html-parsing beautifulsoup

有没有办法在BeautifulSoup

中写这个
for node in soup:
  if node is in ["a", "b", "i", ...]: # node is tag of type `a` or `b` ...
    # we are probably on the text level
    textLevelFlag = true
  else:
    # "we are higher"

1 个答案:

答案 0 :(得分:1)

如果您想测试您的代码是否只有文字元素,可以试试这个:

if hasattr(node, contents) and len(node.contents) == 1 and isinstance(node.contents[0], NavigableString):
    textLevelFlag = true
else:
    something else