【问题标题】:Beautiful Soup: Only target elements if a specific child has a certain classBeautiful Soup:仅当特定孩子有某个班级时才针对元素
【发布时间】:2016-02-14 00:25:58
【问题描述】:

我正在做一些python/beautiful soup练习来练习,我遇到了一个我正在努力解决的问题:我想遍历一系列标签,但只有在以下情况下才抓取内容它包含一个具有特定类的子标签

我正在解析一个包含体育比分的页面,找到所有<section class="game"> 标签并抓取其中的表格。问题是我只想定位<section> 内部有<div> 并应用class="game-status final " 的标签。 (“final”后面的空格是故意的;页面上是这样的。)

以下是 HTML 的示例:

<section class="game">
    <h3>Team No. 1 vs Team No. 2</h3>
    <div class="game-contents">
        <div class="game-status final ">Final</div>
        <div class="game-championship"></div>
        <div class="linescore">
            <table class="linescore">
                <!-- TABLE CONTENTS -->
            </table>
        </div>
        <div class="links final "></div>
    </div>
</section>

在游戏进入决赛之前,div.game-contents 下的第一个div&lt;div class="game-status"&gt;,所以这就是为什么我要检查这个标签以确定游戏是否是最终的——因此应该被删除。

这是我用来抓取这些表格的代码:

games = soup.find_all('section', class_='game')

list_of_games = []
for game in games:
    list_of_rows = []
    rows = game.find_all('tr')[1:]
    for row in rows:
        list_of_cells = []
        cells = row.find_all('td')
        for cell in cells:
            if 'school' in cell.attrs['class']:
                team = cell.find('a').text
                list_of_cells.append(team)
            elif 'final' in cell.attrs['class']:
                score = cell.text
                list_of_cells.append(score)
        list_of_rows.append(list_of_cells)
    list_of_games.append(list_of_rows)

显然,我需要引入新的逻辑来确定&lt;section&gt; 在被刮除之前是否具有正确的属性,但对于最佳的继续操作方式,我还是一头雾水。

我们将不胜感激任何帮助或指导!

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    找到divfinal 类,如果是None,则跳过此行:

    games = soup.find_all('section', class_='game')
    
    list_of_games = []
    for game in games:
        if game.find("div", class_="final") is None:
            continue
        # rest of the code
    

    【讨论】:

    • 快速简单。完美的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2012-10-23
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多