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

时间:2010-07-03 17:59:19

标签: python html text-extraction

我知道像html2text,BeautifulSoup等的utils,但问题是他们也提取javascript并将其添加到文本中,这使得分离它们变得很困难。

htmlDom = BeautifulSoup(webPage)

htmlDom.findAll(text=True)

或者,

from stripogram import html2text
extract = html2text(webPage)

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

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

4 个答案:

答案 0 :(得分:5)

如果您想避免使用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),以便我可以让所有孩子按顺序完成并自行过滤。

答案 1 :(得分:1)

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

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

Removing Elements

答案 2 :(得分:0)

使用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 :(得分:0)