我想使用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)

其他回答

有人尝试过bleach.clean(html,tags=[],strip=True)与漂白剂吗?这对我很有用。

你也可以在stripogram库中使用html2text方法。

from stripogram import html2text
text = html2text(your_html_string)

需要安装stripogram,请执行sudo easy_install stripogram命令

我发现的最好的一段代码提取文本没有javascript或不想要的东西:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urlopen(url).read()
soup = BeautifulSoup(html, features="html.parser")

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text)

你只需要安装BeautifulSoup:

pip install beautifulsoup4

我使用Apache Tika取得了很好的结果。它的目的是从内容中提取元数据和文本,因此底层解析器要进行相应的开箱即用调优。

Tika可以作为服务器运行,在Docker容器中运行/部署很简单,并且可以通过Python绑定访问。

我推荐一个名为goose-extractor的Python包 Goose将尝试提取以下信息:

文章的正文 文章主图 任何Youtube/Vimeo电影嵌入文章 元数据描述 元标记

更多:https://pypi.python.org/pypi/goose-extractor/