我想使用Python从HTML文件中提取文本。我想从本质上得到相同的输出,如果我从浏览器复制文本,并将其粘贴到记事本。

我想要一些更健壮的东西,而不是使用正则表达式,正则表达式可能会在格式不佳的HTML上失败。我见过很多人推荐Beautiful Soup,但我在使用它时遇到了一些问题。首先,它会抓取不需要的文本,比如JavaScript源代码。此外,它也不解释HTML实体。例如,我会期望'在HTML源代码中转换为文本中的撇号,就像我将浏览器内容粘贴到记事本一样。

更新html2text看起来很有希望。它正确地处理HTML实体,而忽略JavaScript。然而,它并不完全生成纯文本;它产生的降价,然后必须转换成纯文本。它没有示例或文档,但代码看起来很干净。


相关问题:

在python中过滤HTML标签并解析实体 在Python中将XML/HTML实体转换为Unicode字符串


当前回答

我知道已经有很多答案了,但是我找到的最优雅、最python化的解决方案在这里进行了部分描述。

from bs4 import BeautifulSoup

text = ' '.join(BeautifulSoup(some_html_string, "html.parser").findAll(text=True))

更新

根据弗雷泽的评论,这里有一个更优雅的解决方案:

from bs4 import BeautifulSoup

clean_text = ' '.join(BeautifulSoup(some_html_string, "html.parser").stripped_strings)

其他回答

Perl方式(对不起妈妈,我永远不会在生产中这样做)。

import re

def html2text(html):
    res = re.sub('<.*?>', ' ', html, flags=re.DOTALL | re.MULTILINE)
    res = re.sub('\n+', '\n', res)
    res = re.sub('\r+', '', res)
    res = re.sub('[\t ]+', ' ', res)
    res = re.sub('\t+', '\t', res)
    res = re.sub('(\n )+', '\n ', res)
    return res

我有一个类似的问题,实际上我用了BeautifulSoup的一个答案。 问题是它真的很慢。我最终使用了一个叫做selectolax的库。 虽然它的功能很有限,但它对这个任务很有效。 唯一的问题是我手动删除了不必要的空白。 但BeautifulSoup的效果似乎要快得多。

from selectolax.parser import HTMLParser

def get_text_selectolax(html):
    tree = HTMLParser(html)

    if tree.body is None:
        return None

    for tag in tree.css('script'):
        tag.decompose()
    for tag in tree.css('style'):
        tag.decompose()

    text = tree.body.text(separator='')
    text = " ".join(text.split()) # this will remove all the whitespaces
    return text

如果你想从网页中自动提取文本段落,有一些可用的python包,如Trafilatura。作为基准测试的一部分,比较了几个python包:

https://github.com/adbar/trafilatura#evaluation-and-alternatives

html_text https://github.com/TeamHG-Memex/html-text inscriptis https://github.com/weblyzard/inscriptis newspaper3k justext boilerpy3 https://github.com/jmriebold/BoilerPy3 基线 goose3 https://github.com/goose3/goose3 readability-lxml https://github.com/predatell/python-readability-lxml news-please https://github.com/fhamborg/news-please readabilipy https://github.com/alan-turing-institute/ReadabiliPy trafilatura

我得到的结果是这样的。

>>> import requests
>>> url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
>>> res = requests.get(url)
>>> text = res.text

注意:NTLK不再支持clean_html函数

下面是原始答案,评论部分有备选答案。


使用NLTK

我浪费了4-5个小时来修复html2text的问题。幸运的是我遇到了NLTK。 它神奇地起作用。

import nltk   
from urllib import urlopen

url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"    
html = urlopen(url).read()    
raw = nltk.clean_html(html)  
print(raw)