Beautifulsoup获得跨度内容

时间:2014-03-07 19:50:14

标签: python html beautifulsoup html-parsing

我已经解析了html页面:使用beautifulsoup

user_page = urllib2.urlopen(user_url)
souping_page = bs(user_page)
badges = souping_page.body.find('div', attrs={'class': 'badges'})

之后我的badges对象看起来像这样:

<span><span title="9 gold badges"><span class="badge1"></span><span class="badgecount">9</span></span><span title="38 silver badges"><span class="badge2"></span><span class="badgecount">38</span></span><span title="56 bronze badges"><span class="badge3"></span><span class="badgecount">56</span></span></span>

现在我想从中提取示例9 gold badges38 silver badges,我尝试使用badges.span.span,但这不起作用。

1 个答案:

答案 0 :(得分:10)

span获取父badges,使用find_all() recursive=False找到所有顶级跨度:

from bs4 import BeautifulSoup


page = """<div class="badges">
<span>
    <span title="9 gold badges"><span class="badge1"></span><span class="badgecount">9</span></span>
    <span title="38 silver badges"><span class="badge2"></span><span class="badgecount">38</span></span>
    <span title="56 bronze badges"><span class="badge3"></span><span class="badgecount">56</span></span>
</span>
</div>"""

soup = BeautifulSoup(page)
badges = soup.body.find('div', attrs={'class': 'badges'})
for span in badges.span.find_all('span', recursive=False):
    print span.attrs['title']

打印:

9 gold badges
38 silver badges
56 bronze badges

希望有所帮助。