我想用Python从HTML文件中提取文本。我想要的输出基本上与从浏览器复制文本并将其粘贴到记事本中得到的输出相同。
我想要一些比使用正则表达式更健壮的东西,因为正则表达式在格式不佳的HTML上可能会失败。我看到很多人推荐Beautiful Soup,但我在使用它时遇到了一些问题。首先,它会拾取不需要的文本,比如JavaScript源。而且,它不能解释HTML实体。例如,我希望‘in HTML source’转换为文本中的撇号,就像我将浏览器内容粘贴到记事本中一样。
更新
看起来很有希望。它正确地处理HTML实体并忽略JavaScript。但是,它并不能准确地生成纯文本;它会生成必须转换为纯文本的markdown。它没有提供示例或文档,但代码看起来很干净。
相关问题:
过滤掉HTML标签并解析python中的实体
在Python中将XML/HTML实体转换为Unicode字符串
我发现自己今天也面临着同样的问题。我编写了一个非常简单的HTML解析器来剥离传入内容的所有标记,只返回仅包含最少格式的剩余文本。
from HTMLParser import HTMLParser
from re import sub
from sys import stderr
from traceback import print_exc
class _DeHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.__text = []
def handle_data(self, data):
text = data.strip()
if len(text) > 0:
text = sub('[ \t\r\n]+', ' ', text)
self.__text.append(text + ' ')
def handle_starttag(self, tag, attrs):
if tag == 'p':
self.__text.append('\n\n')
elif tag == 'br':
self.__text.append('\n')
def handle_startendtag(self, tag, attrs):
if tag == 'br':
self.__text.append('\n\n')
def text(self):
return ''.join(self.__text).strip()
def dehtml(text):
parser = _DeHTMLParser()
parser.feed(text)
parser.close()
return parser.text()
except:
print_exc(file=stderr)
return text
def main():
text = r'''
Project: DeHTML
Description:
This small script is intended to allow conversion from HTML markup to
plain text.
print(dehtml(text))
if __name__ == '__main__':
main()
请查看htmllib,而不是HTMLParser模块。它有一个类似的界面,但为你做了更多的工作。(它非常古老,所以在摆脱javascript和css方面帮助不大。您可以创建一个派生类,但可以添加名称为start的方法
_
脚本和结束
_
样式(有关详细信息,请参阅python文档),但对于格式错误的html,很难可靠地做到这一点。)无论如何,这里有一些简单的方法可以将纯文本打印到控制台
from htmllib import HTMLParser, HTMLParseError
from formatter import AbstractFormatter, DumbWriter
p = HTMLParser(AbstractFormatter(DumbWriter()))
try: p.feed('hello
there'); p.close() #calling close is not usually needed, but let's play it safe
except HTMLParseError: print ':(' #the html is badly malformed (or you found a bug)
这不是一个确切的Python解决方案,但它会将Javascript生成的文本转换为文本,我认为这一点很重要(例如google.com)。浏览器链接(不是Lynx)具有Javascript引擎,并将使用-dump选项将源文件转换为文本。
所以你可以这样做:
fname = os.tmpnam()
fname.write(html_source)
proc = subprocess.Popen(['links', '-dump', fname],
stdout=subprocess.PIPE,
stderr=open('/dev/null','w'))
text = proc.stdout.read()
Beautiful确实可以转换html实体。考虑到HTML经常有buggy,并且充满了unicode和html编码问题,这可能是您最好的选择。这是我用来将html转换成原始文本的代码:
import BeautifulSoup
def getsoup(data, to_unicode=False):
data = data.replace(" ", " ")
# Fixes for bad markup I've seen in the wild. Remove if not applicable.
masssage_bad_comments = [
(re.compile(''), lambda match: ''),
myNewMassage = copy.copy(BeautifulSoup.BeautifulSoup.MARKUP_MASSAGE)
myNewMassage.extend(masssage_bad_comments)
return BeautifulSoup.BeautifulSoup(data, markupMassage=myNewMassage,
convertEntities=BeautifulSoup.BeautifulSoup.ALL_ENTITIES
if to_unicode else None)
remove_html = lambda c: getsoup(c, to_unicode=True).getText(separator=u' ') if c else ""
下面是xperroni的答案的一个版本,它更完整一些。它跳过脚本和样式部分,并转换charrefs (例如,')和HTML实体(例如,&)。
它还包括一个普通的纯文本到html的反向转换器。
"""
HTML <-> text conversions.
from HTMLParser import HTMLParser, HTMLParseError
from htmlentitydefs import name2codepoint
import re
class _HTMLToText(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self._buf = []
self.hide_output = False
def handle_starttag(self, tag, attrs):
if tag in ('p', 'br') and not self.hide_output:
self._buf.append('\n')
elif tag in ('script', 'style'):
self.hide_output = True
def handle_startendtag(self, tag, attrs):
if tag == 'br':
self._buf.append('\n')
def handle_endtag(self, tag):
if tag == 'p':
self._buf.append('\n')
elif tag in ('script', 'style'):
self.hide_output = False
def handle_data(self, text):
if text and not self.hide_output:
self._buf.append(re.sub(r'\s+', ' ', text))
def handle_entityref(self, name):
if name in name2codepoint and not self.hide_output:
c = unichr(name2codepoint[name])
self._buf.append(c)
def handle_charref(self, name):
if not self.hide_output:
n = int(name[1:], 16) if name.startswith('x') else int(name)
self._buf.append(unichr(n))
def get_text(self):
return re.sub(r' +', ' ', ''.join(self._buf))
def html_to_text(html):
Given a piece of HTML, return the plain text it contains.
This handles entities and char refs, but not javascript and stylesheets.
parser = _HTMLToText()
parser.feed(html)
parser.close()
except HTMLParseError:
return parser.get_text()
def text_to_html(text):
Convert the given text to html, wrapping what looks like URLs with tags,
converting newlines to
tags and converting confusing chars into html
entities.
def f(mo):
t = mo.group()
if len(t) == 1:
return {'&':'&', "'":''', '"':'"', '<':'<', '>':'>'}.get(t)
return '%s' % (t, t)
return re.sub(r'https?://[^] ()"\';]+|[&\'"<>]', f, text)
在Python3.x中,你可以通过导入'imaplib‘和'email’包,以一种非常简单的方式做到这一点。虽然这是一个较老的帖子,但也许我的答案可以帮助这个帖子的新手。
status, data = self.imap.fetch(num, '(RFC822)')
email_msg = email.message_from_bytes(data[0][1])
#email.message_from_string(data[0][1])
#If message is multi part we only want the text version of the body, this walks the message and gets the body.
if email_msg.is_multipart():
for part in email_msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True) #to control automatic email-style MIME decoding (e.g., Base64, uuencode, quoted-printable)
body = body.decode()
elif part.get_content_type() == "text/html":
continue
现在您可以打印主体变量,它将是明文格式:)如果它对您来说足够好,那么选择它作为可接受的答案将是很好的。
另一种选择是通过基于文本的web浏览器运行html并将其转储。例如(使用Lynx):
lynx -dump html_to_convert.html > converted_html.txt
这可以在python脚本中完成,如下所示:
import subprocess
with open('converted_html.txt', 'w') as outputFile:
subprocess.call(['lynx', '-dump', 'html_to_convert.html'], stdout=testFile)
它不会准确地给出HTML文件中的文本,但根据您的用例,它可能比html2text的输出更可取。
我知道已经有很多答案了,但最重要的是
优雅
和
pythonic式
我找到的解决方案部分地描述了,
这里
..。
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)
@PeYoTIL的答案是使用BeautifulSoup并删除样式和脚本内容,对我来说不起作用。我试过了,用的是
而不是
但它仍然不起作用。所以我创建了我自己的,它也使用
标记和替换
带有href链接的标签。还可以处理文本中的链接。可在
这个要点
嵌入了测试文档。
from bs4 import BeautifulSoup, NavigableString
def html_to_text(html):
"Creates a formatted text email message as a string from a rendered html template (page)"
soup = BeautifulSoup(html, 'html.parser')
# Ignore anything in head
body, text = soup.body, []
for element in body.descendants:
# We use type and not isinstance since comments, cdata, etc are subclasses that we don't want
if type(element) == NavigableString:
# We use the assumption that other tags can't be inside a script or style
if element.parent.name in ('script', 'style'):
continue
# remove any multiple and leading/trailing whitespace
string = ' '.join(element.string.split())
if string:
if element.parent.name == 'a':
a_tag = element.parent
# replace link text with the link
string = a_tag['href']
# concatenate with any non-empty immediately previous string
if ( type(a_tag.previous_sibling) == NavigableString and
a_tag.previous_sibling.string.strip() ):
text[-1] = text[-1] + ' ' + string
continue
elif element.previous_sibling and element.previous_sibling.name == 'a':
text[-1] = text[-1] + ' ' + string
continue
elif element.parent.name == 'p':
# Add extra paragraph formatting newline
string = '\n' + string
text += [string]
doc = '\n'.join(text)
return doc
下面是我经常使用的代码。
from bs4 import BeautifulSoup
import urllib.request
def processText(webpage):
# EMPTY LIST TO STORE PROCESSED TEXT
proc_text = []
news_open = urllib.request.urlopen(webpage.group())
news_soup = BeautifulSoup(news_open, "lxml")
news_para = news_soup.find_all("p", text = True)
for item in news_para:
# SPLIT WORDS, JOIN WORDS TO REMOVE EXTRA SPACES
para_text = (' ').join((item.text).split())
# COMBINE LINES/PARAGRAPHS INTO A LIST
proc_text.append(para_text)
except urllib.error.HTTPError:
return proc_text
我希望这能有所帮助。
我知道这里已经有很多答案了,但我认为
newspaper3k
同样值得一提的是。我最近需要完成一个类似的任务,从web上的文章中提取文本,到目前为止,这个库在我的测试中完成了很好的工作。它忽略菜单项和侧边栏中的文本,以及在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
虽然很多人提到使用regex来剥离html标签,但也有很多缺点。
例如:
hello worldI love you
应解析为:
Hello world
I love you
这是我想出来的一个片段,你可以根据你的特定需求来讨论它,它就像一个护身符
import re
import html
def html2text(htm):
ret = html.unescape(htm)
ret = ret.translate({
8209: ord('-'),
8220: ord('"'),
8221: ord('"'),
160: ord(' '),
ret = re.sub(r"\s", " ", ret, flags = re.MULTILINE)
ret = re.sub("
|||", "\n", ret, flags = re.IGNORECASE)
ret = re.sub('<.*?>', ' ', ret, flags=re.DOTALL)
ret = re.sub(r" +", " ", ret)
return ret
在Python 2.7.9+中使用BeautifulSoup4的另一个示例
包括:
import urllib2
from bs4 import BeautifulSoup
代码:
def read_website_to_text(url):
page = urllib2.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
for script in soup(["script", "style"]):
script.extract()
text = soup.get_text()
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
return str(text.encode('utf-8'))
解释:
以.get格式读取url数据(使用BeautifulSoup),删除所有脚本和样式元素,并使用html仅获取文本
_
text()。将多个标题拆分为几行并删除其中的前导空格和尾随空格,然后将多个标题拆分为一行each chunks = (phrase.strip() for line in line for phrase in line.split(“"))。然后使用text = '\n'.join,删除空行,最后作为认可的utf-8返回。
备注:
由于SSL问题,运行此命令的某些系统将失败,并显示https://连接,您可以关闭验证来修复该问题。示例修复:
http://blog.pengyifan.com/how-to-fix-python-ssl-certificate
_
验证
_
失败/
Python < 2.7.9在运行以下代码时可能会遇到一些问题
text.encode('utf-8')可能会留下奇怪的编码,可能只想返回字符串(文本)。
我有一个类似的问题,实际上我在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()