2015-10-15 9 views
6

This questionは4年前に尋ねられましたが、答えは現在BS4のために古くなっています。美味しいスープですべてのコメントを見つける方法

美しいスープを使ってHTMLファイルのコメントをすべて削除します。 BS4は、各comment as a special type of navigable stringを作るので、私はこのコードが動作するだろうと思った:

for comments in soup.find_all('comment'): 
    comments.decompose() 

だから、私はすべてのコメントはBS4を使用して見つけるにはどうすればよいです....動作しませんでしたか?私が行うために必要な

+0

この回答(http://stackoverflow.com/a/3507360/771848)は、私が推測しているはずです。 – alecxe

+0

グローバル名のコメントが定義されていません。 – Joseph

+1

これは古いですが、@Joseph、bs4からコメントをインポートすると正常に動作するはずです – atarw

答えて

8

を抽出するためのコードだとき、あなたはfind_allする関数を渡すことができます()を使用して、文字列がコメントかどうかを確認します。私はhtmlの下に持っ例えば

<body> 
    <!-- Branding and main navigation --> 
    <div class="Branding">The Science &amp; Safety Behind Your Favorite Products</div> 
    <div class="l-branding"> 
     <p>Just a brand</p> 
    </div> 
     <!-- test comment here --> 
     <div class="block_content"> 
      <a href="https://www.google.com">Google</a> 
    </div> 
</body> 

コード:

from bs4 import BeautifulSoup as BS 
from bs4 import Comment 
.... 
soup=BS(html,'html.parser') 
comments=soup.find_all(string=lambda text:isinstance(text,Comment)) 
for c in comments: 
    print c 
    print "===========" 
    c.decompose() 

出力は次のようになります。

Branding and main navigation 
============ 
test comment here 
============ 

ところで、私はfind_all('Comment')がない理由を考えます仕事は(BeautifulSoupドキュメントから):

名前の値を渡すと、Beautiful Soupに特定の名前のタグのみが考慮されるようになります。 文字列は無視されます。は、名前が一致しないタグと同じです。

+0

私はあなたの答えを見つけてうれしいです、ありがとう!私たちがラムダを使わずにどのように書くことができるか考えてみませんか? – JinSnow

6

2つのこと:

まず、美しいスープをインポート

第二には、ここでコメント

for comments in soup.findAll(text=lambda text:isinstance(text, Comment)): 
    comments.extract() 
関連する問題