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

标签 python html text-extraction

我知道 html2text、BeautifulSoup 等实用程序,但问题是它们还提取 javascript 并将其添加到文本中,这使得很难将它们分开。

htmlDom = BeautifulSoup(webPage)

htmlDom.findAll(text=True)

或者,

from stripogram import html2text
extract = html2text(webPage)

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

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

最佳答案

如果你想避免使用 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),这样我就可以按顺序获取所有子项并进行我自己的过滤。

关于python - 使用 Python 从 HTML 中提取可读文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3172343/

相关文章:

python - Python 中的 getpass.getpass() 函数不起作用?

python - 字典键*值到python中的列表

javascript - 计算 slider 的视口(viewport)高度

html - Firefox 和 Chrome 中的文本区域填充不一致

html - 移动表格帮助 facebook 风格

python - 有监督的文本抽取摘要

python - 从列表中随机删除 'x' 个元素

java - 如何提取IP :PORT from strings java

ios - 从 objective-c 中的字符串的右侧提取

python - 名称错误 : name 'datetime' is not defined