1

要素のリストを取得したり、タグの文字列を取得したりして、beautifulSoup parsetree を分割するさまざまな方法があります。しかし、分割中にツリーをそのままにしておく方法はないようです。

次のスニペット (スープ) を で分割したいと思い<br />ます。文字列では些細なことですが、構造を維持したいので、パースツリーのリストが必要です。

s="""<p>
foo<br />
<a href="http://...html" target="_blank">foo</a> | bar<br />
<a href="http://...html" target="_blank">foo</a> | bar<br />
<a href="http://...html" target="_blank">foo</a> | bar<br />
<a href="http://...html" target="_blank">foo</a> | bar
</p>"""
soup=BeautifulSoup(s)

もちろん、私は を行うことができますが[BeautifulSoup(i) for i in str(soup).split('<br />')]、それは醜く、そのためのリンクが多すぎます。

soup.findAll('br') でのsoup.next およびsoup.previousSibling() の反復は可能ですが、パースツリーではなく、それに含まれるすべての要素のみを返します。

すべての親と兄弟の関​​係を維持しながら、BeautifulSoup タグからタグの完全なサブツリーを抽出するソリューションはありますか?

より明確にするために編集します。

結果は BeautifulSoup-Objects で構成されるリストになるはずで、分割されたスープをさらに下へ、output[0].a、output[1].text などでトラバースできます。sでスープを分割すると、<br />さらに処理するすべてのリンクのリストが返されます。これが必要です。上記のスニペットからのすべてのリンク。テキスト、属性、および各リンクの説明である次の「バー」を含みます。

4

1 に答える 1

0

元のツリーが変更されても構わない場合は.extract()、タグで使用して<br />、ツリーから単純に削除します。

>>> for br in soup.find_all('br'): br.extract()
... 
<br/>
<br/>
<br/>
<br/>
>>> soup
<html><body><p>
foo
<a href="http://...html" target="_blank">foo</a> | bar
<a href="http://...html" target="_blank">foo</a> | bar
<a href="http://...html" target="_blank">foo</a> | bar
<a href="http://...html" target="_blank">foo</a> | bar
</p></body></html>

これはまだ完全な作業ツリーです:

>>> soup.p
<p>
foo
<a href="http://...html" target="_blank">foo</a> | bar
<a href="http://...html" target="_blank">foo</a> | bar
<a href="http://...html" target="_blank">foo</a> | bar
<a href="http://...html" target="_blank">foo</a> | bar
</p>
>>> soup.p.a
<a href="http://...html" target="_blank">foo</a>

ただし、目的を達成するためにこれらのタグをまったく削除する必要はありません。

for link in soup.find_all('a'):
    print link['href'], ''.join(link.stripped_strings), link.next_sibling

結果:

>>> for link in soup.find_all('a'):
...     print link['href'], ''.join(link.stripped_strings), link.next_sibling
... 
http://...html foo  | bar
http://...html foo  | bar
http://...html foo  | bar
http://...html foo  | bar

<br/>最初にツリーからタグを削除したかどうかに関係なく。

于 2013-03-04T14:52:17.977 に答える