HTMLソースのコメントをPythonで抽出し、コメントを削除

1274 ワード

プログラミングの問題に遭遇すると、まず考えなければならないのは、それを簡略化し、最も簡単な問題に簡略化した後、最も簡単なコードを書いて解決し、同時に最も簡単なテストの代価だけを払うことです.
簡単なHTMLソース:
1<!--The loneliest number-->
                        <a>2<!--Can be as bad as one--><b>3

上記のコードのコメントを抽出します.
from bs4 import BeautifulSoup, Comment

soup = BeautifulSoup("""1<!--The loneliest number-->
                        <a>2<!--Can be as bad as one--><b>3""")
comments = soup.findAll(text=lambda text:isinstance(text, Comment))

for comment in comments:
    print comment

出力結果:
The loneliest number
Can be as bad as one

上のHTMLコードのコメントを削除します.
from bs4 import BeautifulSoup, Comment

soup = BeautifulSoup("""1<!--The loneliest number-->
                        <a>2<!--Can be as bad as one--><b>3""")
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in comments]
print soup

出力結果:
1
<a>2<b>3</b></a>

参照先:
1、How to find the comment tag with BeautifulSoup?
2、BeautifulSoup documentation #Removing elements