を次の要素を取得するために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"/>]
セキュリティに関しては、ホワイトリストが最適です! –