美丽的汤:只有目标元素,如果一个特定的孩子有一个特定的类
问题描述:
我正在做一些蟒蛇/美丽的汤练习的练习,我遇到了一个问题,我正在努力解决:我想迭代通过一系列标签,但只有在其中包含具有特定类别的子标签的内容时才会进行擦除。美丽的汤:只有目标元素,如果一个特定的孩子有一个特定的类
我正在解析一个带有体育比分的页面,找到所有<section class="game">
标签并将其中的表格刮掉。问题是我只想瞄准内部应用了class="game-status final "
的<div>
的<section>
标签。 (在“最终”的空间是故意的,这就是它是如何在页面上。)
这里的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>
有正确的性质它刮掉过,但我画一个空白作以最好的方式进行。
任何帮助或指导在这里将不胜感激!
答
找到div
与final
类,如果是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
方便快捷。完善。谢谢! – chrismlusk