2017-02-02 7 views
2

htmlコードがあると、どのようにしてすべてのタグを削除できますか?例えば、私は私がBeautifulSoup「img」や「a」のようなホワイトリストにあるものを除いて、すべてのhtmlタグを削除します

Hello to <a href ="xx"></a> <img rscr="xx"></img> 

を維持したい

<div><script bla bla></script><p>Hello all <a href ="xx"></a> <img rscr="xx"></img></p></div> 

がBeautifulSoupやPythonで実装何かがあり がありますか?

おかげ

+0

セキュリティに関しては、ホワイトリストが最適です! –

答えて

0

を次の要素を取得するためにfind_nextを使用することができますになります.descendants propertyにアクセスしてください。

そこからすべての子孫を反復し、nameプロパティに基づいてフィルタリングできます。ノードにnameプロパティがない場合は、保持する可能性が高いテキストノードです。 nameプロパティがaまたはimgの場合は、それも保持します。ここで

# This should be the wrapper that you are targeting 
container = soup.find('div') 
keep = [] 

for node in container.descendants: 
    if not node.name or node.name == 'a' or node.name == 'img': 
    keep.append(node) 

は、すべてのフィルタ要素が直接リストを作成するために使用される代替手段です。

# This should be the wrapper that you are targeting 
container = soup.find('div') 

keep = [node for node in container.descendants 
     if not node.name or node.name == 'a' or node.name == 'img'] 

また、あなたが返される空になっている文字列を使用しない場合、あなたはトリミングすることができます空白と同様にそれをチェック:

keep = [node for node in container.descendants 
     if (not node.name and len(node.strip())) or 
      (node.name == 'a' or node.name == 'img')] 

をご提供HTMLに基づき、以下が返されます:

> ['Hello all ', <a href="xx"></a>, <img rscr="xx"/>] 
0
import bs4 

html = '''<div><script bla bla></script><p>Hello all <a href ="xx"></a> <img rscr="xx"></img></p></div>''' 

soup = bs4.BeautifulSoup(html, 'lxml') 
soup.div.text, soup.div.find_next('a'), soup.div.find_next('img') 

アウト:

soup.div.text, soup.div.a, soup.div.img 

アウト:

('Hello all ', <a href="xx"></a>, <img rscr="xx"/>) 
次の要素は、タグの子孫である場合には、ショートカットがあり

('Hello all ', <a href="xx"></a>, <img rscr="xx"/>) 

  1. あなたはBS4のパーサーを使用する場合、「IMG」タグは、自己閉じタグ
  2. あなたが遠かったあなたがで子孫ノードのすべてを選択することができDOMに
+0

私に「

Hello all

」があったらどうしますか?あなたのコードは、見つかった最初のタグのみを返します。文字列は一例に過ぎず、私はウェブページ全体を解析する必要があります。 – f126ck

+0

@ f126ckあなたはurlとあなたが望む出力で質問を更新します –

関連する問題