2016-02-14 39 views
1

我正在做一些蟒蛇/美麗的湯練習的練習,我遇到了一個問題,我正在努力解決:我想迭代通過一系列標籤,但只有在其中包含具有特定類別的子標籤的內容時纔會進行擦除。美麗的湯:只有目標元素,如果一個特定的孩子有一個特定的類

我正在解析一個帶有體育比分的頁面,找到所有<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> 

比賽進入決賽前,首先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>有正確的性質它刮掉過,但我畫一個空白作以最好的方式進行。

任何幫助或指導在這裏將不勝感激!

回答

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 
+0

方便快捷。完善。謝謝! – chrismlusk

相關問題