導入
HTML データを操作する場合、多くの場合、タグをクリーンアップしてプレーン テキストのみを保持する必要があります。データ分析、自動化、または単にコンテンツを読みやすくするためのいずれであっても、このタスクは開発者にとって一般的なものです。
この記事では、組み込みの Python モジュールである HTMLParser を使用して、HTML からプレーン テキストを抽出する簡単な Python クラスを作成する方法を説明します。
HTMLParser を使用する理由
HTMLParser は、HTML ドキュメントの解析と操作を可能にする軽量の組み込み Python モジュールです。 BeautifulSoup のような外部ライブラリとは異なり、軽量で、HTML タグのクリーニングなどの単純なタスクに最適です。
解決策: 単純な Python クラス
ステップ 1: HTMLTextExtractor クラスを作成する
from html.parser import HTMLParser class HTMLTextExtractor(HTMLParser): """Class for extracting plain text from HTML content.""" def __init__(self): super().__init__() self.text = [] def handle_data(self, data): self.text.append(data.strip()) def get_text(self): return ''.join(self.text)
このクラスは主に 3 つのことを行います。
- 抽出されたテキストを保存するためにリスト self.text を初期化します。
- handle_data メソッドを使用して、HTML タグ間にあるすべてのプレーン テキストをキャプチャします。
- get_text メソッドを使用してすべてのテキスト フラグメントを結合します。
ステップ 2: クラスを使用してテキストを抽出する
クラスを使用して HTML をクリーンアップする方法は次のとおりです。
raw_description = """ <div> <h1 id="Welcome-to-our-website">Welcome to our website!</h1> <p>We offer <strong>exceptional services</strong> for our customers.</p> <p>Contact us at: <a href="mailto:contact@example.com">contact@example.com</a></p> </div> """ extractor = HTMLTextExtractor() extractor.feed(raw_description) description = extractor.get_text() print(description)
出力:
Welcome to our website! We offer exceptional services for our customers.Contact us at: contact@example.com
属性のサポートの追加
タグ内のリンクなどの追加情報を取得したい場合は、クラスの拡張バージョンを次に示します。
class HTMLTextExtractor(HTMLParser): """Class for extracting plain text and links from HTML content.""" def __init__(self): super().__init__() self.text = [] def handle_data(self, data): self.text.append(data.strip()) def handle_starttag(self, tag, attrs): if tag == 'a': for attr, value in attrs: if attr == 'href': self.text.append(f" (link: {value})") def get_text(self): return ''.join(self.text)
拡張出力:
Welcome to our website!We offer exceptional services for our customers.Contact us at: contact@example.com (link: mailto:contact@example.com)
## Use Cases - **SEO**: Clean HTML tags to analyze the plain text content of a webpage. - **Emails**: Transform HTML emails into plain text for basic email clients. - **Scraping**: Extract important data from web pages for analysis or storage. - **Automated Reports**: Simplify API responses containing HTML into readable text.
このアプローチの利点
- 軽量: 外部ライブラリは必要ありません。これは Python のネイティブ HTMLParser に基づいて構築されています。
- 使いやすさ: シンプルで再利用可能なクラスにロジックをカプセル化します。
- カスタマイズ可能: 機能を簡単に拡張して、属性や追加のタグ データなどの特定の情報を取得します。
## Limitations and Alternatives While `HTMLParser` is simple and efficient, it has some limitations: - **Complex HTML**: It may struggle with very complex or poorly formatted HTML documents. - **Limited Features**: It doesn't provide advanced parsing features like CSS selectors or DOM tree manipulation. ### Alternatives If you need more robust features, consider using these libraries: - **BeautifulSoup**: Excellent for complex HTML parsing and manipulation. - **lxml**: Known for its speed and support for both XML and HTML parsing.
結論
このソリューションを使用すると、わずか数行のコードで HTML からプレーン テキストを簡単に抽出できます。個人的なプロジェクトに取り組んでいる場合でも、専門的なタスクに取り組んでいる場合でも、このアプローチは軽量の HTML のクリーニングと分析に最適です。
使用例に、より複雑な HTML や不正な形式の HTML が含まれる場合は、機能を強化するために BeautifulSoup や lxml などのライブラリの使用を検討してください。
このコードをプロジェクトで自由に試して、経験を共有してください。コーディングを楽しんでください! ?
以上がPython で HTML コンテンツからテキストを抽出: `HTMLParser` を使用した簡単なソリューションの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

pythonusesahybridapproach、コンコイリティレーショントビテコードと解釈を組み合わせて、コードコンピレッドフォームと非依存性bytecode.2)

keydifferencesは、「for」と「while "loopsare:1)" for "for" loopsareideal forterating overencesonownowiterations、while2) "for" for "for" for "for" for "for" for "for" for for for for "wide" loopsarebetterunuinguntinunuinguntinisisisisisisisisisisisisisisisisisisisisisisisisisisisations.un

Pythonでは、さまざまな方法でリストを接続して重複要素を管理できます。1)オペレーターを使用するか、すべての重複要素を保持します。 2)セットに変換してから、リストに戻ってすべての重複要素を削除しますが、元の順序は失われます。 3)ループを使用するか、包含をリストしてセットを組み合わせて重複要素を削除し、元の順序を維持します。

fasteStMethodDodforListConcatenationinpythOndontsonistize:1)forsmallLists、operatorisefficient.2)forlargerlists、list.extend()orlistcomlethingisfaster、withextend()beingmorememory-efficient bymodifyigniviselistinistin-place。

to insertelementsIntopeaseThonList、useappend()toaddtotheend、insert()foraspificposition、andextend()formultipleElements.1)useappend()foraddingsingleitemstotheend.2)useintert()toaddataspecificindex、cont'slowerforforgelists.3)

PythonListsareimplementedasdynamicarrays、notlinkedlists.1)they restorediguourmemoryblocks、それはパフォーマンスに影響を与えることに影響を与えます

pythonoffersfourmainmethodstoremoveelements fromalist:1)removesthefirstoccurrenceofavalue、2)pop(index(index(index)removes regvess returnsaspecifiedindex、3)delstatementremoveselementselementsbyindexorseLice、および4)clear()

toresolvea "許可denided" errors whenrunningascript、sofflowthesesteps:1)checkandadaddadaddadadaddaddadadadaddadaddadaddadaddaddaddaddaddadaddadaddaddaddaddadaddaddaddadadaddadaddadaddadadisionsisingmod xmyscript.shtomakeitexexutable.2)


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

ドリームウィーバー CS6
ビジュアル Web 開発ツール

WebStorm Mac版
便利なJavaScript開発ツール
