あなたはこのようなことを試すことができます。それは基本的にあなたが上でしたことをします-最初にすべての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'}