编程语言
首页 > 编程语言> > 使用Python从HTML中提取可读文本?

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

作者:互联网

我知道像html2text,BeautifulSoup等的utils,但问题是他们也提取javascript并将其添加到文本中,因此很难将它们分开.

htmlDom = BeautifulSoup(webPage)

htmlDom.findAll(text=True)

交替,

from stripogram import html2text
extract = html2text(webPage)

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

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

解决方法:

如果您想避免使用BeautifulSoup提取脚本标记的任何内容,

nonscripttags = htmlDom.findAll(lambda t: t.name != 'script', recursive=False)

会为你做到这一点,让root的直接子节点是非脚本标签(和一个单独的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,html,text-extraction
来源: https://codeday.me/bug/20190606/1190442.html