python - BeautifulSoup : Only target elements if a specific child has a certain class

标签 python beautifulsoup

我正在做一些 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>

比赛进入决赛前,第一个divdiv.game-contents<div class="game-status"> ,所以这就是为什么我想检查此标签以确定游戏是否是最终版本 - 因此应该被删除。

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

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)

显然我需要引入新的逻辑来确定<section>是否在被抓取之前具有正确的属性,但我对继续的最佳方法一无所知。

如果您能提供任何帮助或指导,我们将不胜感激!

最佳答案

找到带有 final 类的 div,如果它是 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

关于python - BeautifulSoup : Only target elements if a specific child has a certain class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386990/

相关文章:

python - GTK - Python Treeview 排序列数据(文件大小 - 字节数据)

python - 使用 numpy 的傅里叶变换找到时间序列最可能的周期性?

Python 和 NLTK : Baseline tagger

python - 如何使用Python在BeautifulSoup中提取同一div中具有相同标签的元素?

python - 高学习率使模型训练失败

python - 当 values_list 有多个元素时从两个列表创建字典

python - 如何通过 class 属性包含空格的 css 选择器匹配特定标签?

python - Beautifulsoup 使用 `find_all` 按文本查找元素,无论其中是否有元素

python - 从循环内的 a.href 获取数据

python - 从 html &lt;script&gt; 中提取 JSON 对象