如何跳过BeautifulSoup中的相同标签 - Python

时间:2013-05-23 13:04:32

标签: python html-parsing web-scraping beautifulsoup

我目前正在为Scrapers编写代码,越来越多的人成为Python的粉丝,特别是BeautifulSoup。

仍然......在通过HTML解析时,我遇到了一个困难的部分,我只能以一种不那么漂亮的方式使用它。

我想抓取HTML代码,尤其是以下代码段:

<div class="title-box">
    <h2>
        <span class="result-desc">
            Search results <strong>1</strong>-<strong>10</strong> out of <strong>10,009</strong> about <strong>paul mccartney</strong><a href="alert/settings" class="title-email-alert-promo x-title-alerts-promo">Create email Alert</a>
        </span>
    </h2>
</div>

所以我所做的就是通过使用

识别div
comment = TopsySoup.find('div', attrs={'class' : 'title-box'})

然后丑陋的部分进来。要抓住我想要的数字:10,009我使用:

catcher = comment.strong.next.next.next.next.next.next.next

有人可以告诉我是否有更好的方式?

1 个答案:

答案 0 :(得分:3)

comment.find_all('strong')[2].text怎么样?

它实际上可以缩短为comment('strong')[2].text,因为调用Tag对象就好像它是一个函数一样,就像在它上面调用find_all一样。

>>> comment('strong')[2].text
u'10,009'