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

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

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


相关问题:

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


当前回答

我发现的最好的一段代码提取文本没有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

其他回答

用一种简单的方式

import re

html_text = open('html_file.html').read()
text_filtered = re.sub(r'<(.*?)>', '', html_text)

这段代码找到了html_text中以'<'开头,以'>'结尾的所有部分,并将所有找到的部分替换为空字符串

另一个非python解决方案:Libre Office:

soffice --headless --invisible --convert-to txt input1.html

我更喜欢这种方法的原因是,每个HTML段落都转换为单个文本行(没有换行符),这正是我所寻找的。其他方法需要后处理。Lynx的输出确实不错,但并不是我想要的。此外,Libre Office可以用来从各种格式转换…

我知道这里已经有很多答案了,但我认为newspaper3k也值得一提。我最近需要完成一个类似的任务,即从网络上的文章中提取文本,到目前为止,这个库在我的测试中完成了出色的工作。它忽略菜单项和边栏中的文本,以及OP请求时出现在页面上的任何JavaScript。

from newspaper import Article

article = Article(url)
article.download()
article.parse()
article.text

如果你已经下载了HTML文件,你可以这样做:

article = Article('')
article.set_html(html)
article.parse()
article.text

它甚至有一些NLP功能来总结文章的主题:

article.nlp()
article.summary

安装html2text using

PIP安装html2text

然后,

>>> import html2text
>>>
>>> h = html2text.HTML2Text()
>>> # Ignore converting links from HTML
>>> h.ignore_links = True
>>> print h.handle("<p>Hello, <a href='http://earth.google.com/'>world</a>!")
Hello, world!

如果您需要更高的速度和更低的准确性,那么您可以使用原始lxml。

import lxml.html as lh
from lxml.html.clean import clean_html

def lxml_to_text(html):
    doc = lh.fromstring(html)
    doc = clean_html(doc)
    return doc.text_content()