【问题标题】:Extracting readable text from HTML using Python?使用 Python 从 HTML 中提取可读文本?
【发布时间】:2010-07-03 17:59:18
【问题描述】:

我知道 html2text、BeautifulSoup 等实用工具,但问题是它们还会提取 javascript 并将其添加到文本中,因此很难将它们分开。

htmlDom = BeautifulSoup(webPage)

htmlDom.findAll(text=True)

或者,

from stripogram import html2text
extract = html2text(webPage)

这两个都提取了页面上的所有javascript,这是不受欢迎的。

我只是想提取可以从浏览器中复制的可读文本。

【问题讨论】:

    标签: python html text-extraction


    【解决方案1】:

    如果您想避免使用 BeautifulSoup 提取 script 标签的任何内容,

    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),这样我就可以按顺序排列所有孩子并进行自己的过滤。

    【讨论】:

    • @demos,不客气,很高兴听到这个消息!顺便说一句,为什么在没有赞成票的情况下接受(以及顺便说一句 tx!)?看起来很奇怪!-)
    • @Alex Martelli 第一个支持来自我。可惜这个答案已经 19 个月没有人投票了!
    【解决方案2】:

    使用 BeautifulSoup,大致如下:

    def _extract_text(t):
        if not t:
            return ""
        if isinstance(t, (unicode, str)):
            return " ".join(filter(None, t.replace("\n", " ").split(" ")))
        if t.name.lower() == "br": return "\n"
        if t.name.lower() == "script": return "\n"
        return "".join(extract_text(c) for c in t)
    def extract_text(t):
        return '\n'.join(x.strip() for x in _extract_text(t).split('\n'))
    print extract_text(htmlDom)
    

    【讨论】:

      【解决方案3】:

      你可以删除美丽汤中的脚本标签,例如:

      for script in soup("script"):
          script.extract()
      

      Removing Elements

      【讨论】:

      • 看起来是一个快速的解决方案,但标签提取的惩罚是什么?
      【解决方案4】:
      猜你喜欢
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 2018-12-08
      • 2011-04-04
      • 2016-05-11
      相关资源
      最近更新 更多