Skip to main content
 首页 » 编程设计

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

2024年10月24日9think

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