5

私は次のhtmlを持っています:

<td class="section">
    <div style="margin-top:2px; margin-bottom:-10px; ">
    <span class="username"><a href="user.php?id=xx">xxUsername</a></span>
    </div>
    <br>
<span class="comment">
A test comment
</span>
</td>

SPANタグ内のxxUsernameとコメントテキストを取得したいすべて。これまで私はこれを行いました:

results = soup.findAll("td", {"class" : "section"})

上記のパターンのすべてのhtmlブロックをフェッチします。ここで、単一のループ内ですべての子の値を取得したいですか?出来ますか?そうでない場合、子ノード情報を取得するにはどうすればよいですか?

4

2 に答える 2

7

あなたはこのようなことを試すことができます。それは基本的にあなたが上でしたことをします-最初にすべてのsectionクラス分けされたものをtd繰り返し、次にその中のすべてのspanテキストを繰り返します。これにより、より制限する必要がある場合に備えて、クラスが出力されます。

In [1]: from bs4 import BeautifulSoup

In [2]: html = # Your html here

In [3]: soup = BeautifulSoup(html)

In [4]: for td in soup.find_all('td', {'class': 'section'}):
   ...:     for span in td.find_all('span'):
   ...:         print span.attrs['class'], span.text
   ...:         
['username'] xxUsername
['comment'] 
A test comment

または、すべてをリストに保存する、必要以上に複雑な1つのライナーを使用します。

In [5]: results = [span.text for td in soup.find_all('td', {'class': 'section'}) for span in td.find_all('span')]

In [6]: results
Out[6]: [u'xxUsername', u'\nA test comment\n']

または、同じテーマで、キーがクラスのタプルであり、値がテキスト自体である辞書:

In [8]: results = dict((tuple(span.attrs['class']), span.text) for td in soup.find_all('td', {'class': 'section'}) for span in td.find_all('span'))

In [9]: results
Out[9]: {('comment',): u'\nA test comment\n', ('username',): u'xxUsername'}

これがあなたが望むものに少し近いと仮定して、私は次のように書き直すことを提案します:

In [10]: results = {}

In [11]: for td in soup.find_all('td', {'class': 'section'}):
   ....:     for span in td.find_all('span'):
   ....:         results[tuple(span.attrs['class'])] = span.text
   ....:         

In [12]: results
Out[12]: {('comment',): u'\nA test comment\n', ('username',): u'xxUsername'}
于 2013-01-27T02:28:43.077 に答える
1

usernameまたはcomment <span>要素からテキストを取得するには:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
for el in soup('span', ['username', 'comment']):
    print el.string,

出力

xxUsername 
A test comment
于 2013-01-27T04:55:40.357 に答える