Pythonを使用してHTMLファイルからテキストを抽出する
-
11-07-2019 - |
質問
Pythonを使用してHTMLファイルからテキストを抽出したいです。ブラウザからテキストをコピーしてメモ帳に貼り付けた場合と基本的に同じ出力が必要です。
不適切な形式のHTMLでは失敗する可能性のある正規表現を使用するよりも堅牢なものが必要です。私は多くの人がBeautiful Soupをお勧めするのを見てきましたが、それを使うのにいくつかの問題がありました。 1つは、JavaScriptソースなどの不要なテキストをピックアップしたことです。また、HTMLエンティティを解釈しませんでした。たとえば、<!> amp;#39;を期待します。ブラウザのコンテンツをメモ帳に貼り付けたかのように、HTMLソースをテキストのアポストロフィに変換します。
更新 html2text
は有望に見えます。 HTMLエンティティを正しく処理し、JavaScriptを無視します。ただし、プレーンテキストを正確に生成するわけではありません。マークダウンを生成し、それをプレーンテキストに変換する必要があります。例やドキュメントはありませんが、コードはきれいに見えます。
関連する質問:
解決
html2text は、これでかなり良い仕事をするPythonプログラムです。
他のヒント
javascriptを取得せずに、または不要なものを使用せずにテキストを抽出するために見つけた最高のコード:
import urllib
from bs4 import BeautifulSoup
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# 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
注: NTLKはclean_html
機能をサポートしなくなりました
以下のオリジナルの回答、およびコメントセクションの代替案。
を使用します
html2textの問題を修正するのに4〜5時間費やしました。幸いなことに、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)
今日、まさに同じ問題に直面している自分を見つけました。すべてのマークアップの受信コンテンツを除去するために非常に単純な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):
try:
parser = _DeHTMLParser()
parser.feed(text)
parser.close()
return parser.text()
except:
print_exc(file=stderr)
return text
def main():
text = r'''
<html>
<body>
<b>Project:</b> DeHTML<br>
<b>Description</b>:<br>
This small script is intended to allow conversion from HTML markup to
plain text.
</body>
</html>
'''
print(dehtml(text))
if __name__ == '__main__':
main()
これは、xperroniの回答のバージョンであり、もう少し完全です。スクリプトセクションとスタイルセクションをスキップし、charref(例:<!> amp;#39;)およびHTMLエンティティ(例:<!> amp; amp;)を変換します。
単純なプレーンテキストから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()
try:
parser.feed(html)
parser.close()
except HTMLParseError:
pass
return parser.get_text()
def text_to_html(text):
"""
Convert the given text to html, wrapping what looks like URLs with <a> tags,
converting newlines to <br> tags and converting confusing chars into html
entities.
"""
def f(mo):
t = mo.group()
if len(t) == 1:
return {'&':'&', "'":''', '"':'"', '<':'<', '>':'>'}.get(t)
return '<a href="%s">%s</a>' % (t, t)
return re.sub(r'https?://[^] ()"\';]+|[&\'"<>]', f, text)
ストリプトグラムライブラリでもhtml2textメソッドを使用できます。
from stripogram import html2text
text = html2text(your_html_string)
stripogramをインストールするには、sudo easy_install stripogramを実行します
すでに多くの答えがあることはわかっていますが、私が見つけた最も優雅および python の解決策の一部は、こちら。
from bs4 import BeautifulSoup
text = ''.join(BeautifulSoup(some_html_string, "html.parser").findAll(text=True))
更新
Fraserのコメントに基づいて、よりエレガントなソリューションを次に示します。
from bs4 import BeautifulSoup
clean_text = ''.join(BeautifulSoup(some_html_string, "html.parser").stripped_strings)
データマイニング用のパターンライブラリがあります。
http://www.clips.ua.ac.be/pages/パターンウェブ
保持するタグを決定することもできます:
s = URL('http://www.clips.ua.ac.be').download()
s = plaintext(s, keep={'h1':[], 'h2':[], 'strong':[], 'a':['href']})
print s
PyParsingは素晴らしい仕事をします。 PyParsing wikiは殺されたので、PyParsingの使用例がある別の場所にあります(リンク例)。 pyparsingに少し時間を費やす理由の1つは、彼が非常に簡潔で非常によく整理されたO'Reilly Short Cutマニュアルも書いていることです。これも安価です。
私はBeautifulSoupを頻繁に使用していますが、エンティティの問題に対処するのはそれほど難しくありません。BeautifulSoupを実行する前に変換できます。
グッドラック
これは正確にPythonのソリューションではありませんが、Javascriptが生成するテキストをテキストに変換します。これは重要だと思います(E.G. 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()
HTMLParserモジュールの代わりに、htmllibをチェックアウトします。同様のインターフェースを備えていますが、より多くの作業を行います。 (かなり古いので、javascriptとcssを取り除くという点ではあまり役に立ちません。派生クラスを作成できますが、start_scriptやend_styleのような名前のメソッドを追加できます(詳細については、Pythonのドキュメントを参照してください)が、難しいとにかく、コンソールにプレーンテキストを出力する簡単なものがあります
from htmllib import HTMLParser, HTMLParseError
from formatter import AbstractFormatter, DumbWriter
p = HTMLParser(AbstractFormatter(DumbWriter()))
try: p.feed('hello<br>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)
より速い速度とより低い精度が必要な場合は、生の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()
を使用して html2text をインストールします
pip install html2text
then、
>>> 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!
美しいスープはhtmlエンティティを変換します。 HTMLはバグが多く、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: '<!--' + match.group(1)),
(re.compile('<!WWWAnswer T[=\w\d\s]*>'), lambda match: '<!--' + match.group(0) + '-->'),
]
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 ""
goose-extractorというPythonパッケージをお勧めします グースは次の情報を抽出しようとします。
記事の本文 記事のメイン画像 記事に埋め込まれたYoutube / Vimeoの映画 メタ記述 メタタグ
もう1つのオプションは、テキストベースの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の出力よりも望ましい場合があります。
別の非Pythonソリューション:Libre Office:
soffice --headless --invisible --convert-to txt input1.html
他の選択肢よりもこれを好む理由は、すべてのHTML段落が単一のテキスト行(改行なし)に変換されるためです。他の方法では後処理が必要です。 Lynxは優れた出力を生成しますが、私が探していたものと正確には一致しません。その上、Libre Officeを使用して、あらゆる種類の形式から変換することができます...
誰もが漂白剤でbleach.clean(html,tags=[],strip=True)
を試みましたか?それは私のために働いています。
すでに多くの回答があることは知っていますが、 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
Apache Tika で良い結果が得られました。その目的は、コンテンツからメタデータとテキストを抽出することであるため、基礎となるパーサーはそのまま使用できます。
Tikaはサーバーとして実行でき、Dockerでの実行/デプロイは簡単です。コンテナから、 Pythonバインディング経由でアクセスできます。
簡単な方法で
import re
html_text = open('html_file.html').read()
text_filtered = re.sub(r'<(.*?)>', '', html_text)
このコードは、 '<!> lt;'で始まるhtml_textのすべての部分を検出します「<!> gt;」で終わる見つかったすべてを空の文字列で置き換えます
@PeYoTILのBeautifulSoupを使用し、スタイルとスクリプトのコンテンツを削除するという答えは、私にとってはうまくいきませんでした。 decompose
の代わりにextract
を使用して試してみましたが、まだ機能しませんでした。そこで、<p>
タグを使用してテキストをフォーマットし、<a>
タグを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
Python 3.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
本文変数を印刷できるようになり、プレーンテキスト形式になります:)それで十分であれば、受け入れられた回答として選択することをお勧めします。
私にとって最も効果的なのは、スクリプトです。
https://github.com/weblyzard/inscriptis
import urllib.request
from inscriptis import get_text
url = "http://www.informationscience.ch"
html = urllib.request.urlopen(url).read().decode('utf-8')
text = get_text(html)
print(text)
結果は本当に良い
BeautifulSoupを使用してHTMLからテキストのみを抽出できます
url = "https://www.geeksforgeeks.org/extracting-email-addresses-using-regular-expressions-python/"
con = urlopen(url).read()
soup = BeautifulSoup(con,'html.parser')
texts = soup.get_text()
print(texts)
多くの人々が正規表現を使用してhtmlタグを削除することについて言及しましたが、多くの欠点があります。
例:
<p>hello world</p>I 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("<br>|<br />|</p>|</div>|</h\d>", "\n", ret, flags = re.IGNORECASE)
ret = re.sub('<.*?>', ' ', ret, flags=re.DOTALL)
ret = re.sub(r" +", " ", ret)
return ret
定期的に使用するコードは次のとおりです。
from bs4 import BeautifulSoup
import urllib.request
def processText(webpage):
# EMPTY LIST TO STORE PROCESSED TEXT
proc_text = []
try:
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:
pass
return proc_text
お役に立てば幸いです。
アプリケーションがpythonマクロを使用できるため、LibreOfficeライターのコメントにはメリットがあります。この質問に答えることとLibreOfficeのマクロベースを促進することの両方に、複数の利点があるようです。この解像度が優れたプロダクションプログラムの一部として使用されるのではなく、1回限りの実装である場合、HTMLをライターで開いてページをテキストとして保存すると、ここで説明する問題が解決されるようです。
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
このようなことを達成しています。
>>> import requests
>>> url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
>>> res = requests.get(url)
>>> text = res.text