如果您想避免script
使用 BeautifulSoup 提取标签的任何内容,
nonscripttags = htmlDom.findAll(lambda t: t.name != 'script', recursive=False)
将为您执行此操作,获取作为非脚本标签的根的直接子代(并且单独的htmlDom.findAll(recursive=False, text=True)
将获取作为根的直接子代的字符串)。您需要递归地执行此操作;例如,作为生成器:
def nonScript(tag):
return tag.name != 'script'
def getStrings(root):
for s in root.childGenerator():
if hasattr(s, 'name'): # then it's a tag
if s.name == 'script': # skip it!
continue
for x in getStrings(s): yield x
else: # it's a string!
yield s
我正在使用childGenerator
(代替findAll
),以便我可以让所有孩子按顺序排列并进行自己的过滤。