1

重複の可能性:
Python で文字列から html を削除する

アプリケーションのような小さなブラウザを作成しているときに、さまざまなタグを分割するという問題に直面しています。文字列を考える

<html> <h1> good morning </h1> welcome </html>

次の出力が必要です: ['おはよう','ようこそ']

どうすればPythonでそれを行うことができますか?

4

3 に答える 3

3

私は使用しますxml.etree.ElementTree

def get_text(etree):
    for child in etree:
        if child.text:
           yield child.text
        if child.tail:
           yield child.tail

import xml.etree.ElementTree as ET
root = ET.fromstring('<html> <h1> good morning </h1> welcome </html>')
print list(get_text(root))
于 2012-10-08T18:19:40.770 に答える
1

pythons html / xml パーサーのいずれかを使用できます。

美しいスープが人気。lmxlも人気です。

上記は、標準ライブラリも使用できるサードパーティのパッケージです

http://docs.python.org/library/xml.etree.elementtree.html

于 2012-10-08T18:10:50.773 に答える
0

Beautiful Soupあなたの目標を達成するためにpythonライブラリを使用します。それは、その助けを借りてほんの数行です:

from bs4 import BeautifulSoup
soup = BeautifulSoup('<html> <h1> good morning </h1> welcome </html>')
print [text for text in soup.stripped_strings]
于 2012-10-08T18:29:44.573 に答える