我正在做一些 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
关于python - BeautifulSoup : Only target elements if a specific child has a certain class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386990/