您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Python从HTML提取可读文本?

使用Python从HTML提取可读文本?

如果您要避免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),以便可以按顺序排列所有子项并进行自己的过滤。

python 2022/1/1 18:44:49 有307人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶