2013-01-24 155 views
0

我正在用Python編寫一個小文本抓取腳本。這是我第一個更大的項目,所以我有一些問題。我使用的是urllib2和BeautifulSoup。我想從一個播放列表中刪除歌曲名稱。我可以得到一首歌曲名稱或所有歌曲名稱+其他字符串,我不需要。我無法得到只有所有歌曲的名字。我的代碼,獲取我並不需要所有的歌曲名稱+其他字符串:BeautifulSoup和正則表達式 - 從標籤中提取文本

import urllib2 
from bs4 import BeautifulSoup 
import re 

response = urllib2.urlopen('http://guardsmanbob.com/media/playlist.php?char=a').read() 
soup = BeautifulSoup(response) 

for tr in soup.findAll('tr')[0]: 
    for td in soup.findAll('a'): 
     print td.contents[0] 

和代碼,給了我一首歌:

print soup.findAll('tr')[1].findAll('a')[0].contents[0] 

它實際上不是一個循環,所以我不能讓不超過一個,但如果我試圖使其循環,我得到了10首相同的歌曲名稱。該代碼:

for tr in soup.findAll('tr')[1]: 
    for td in soup.findAll('td')[0]: 
     print td.contents[0] 

我被困一天了,我無法得到它的工作。我不明白這些東西是如何工作的。

回答

1
for tr in soup.findAll('tr'): # 1 
    if not tr.find('td'): continue # 2 
    for td in tr.find('td').findAll('a'): # 3 
     print td.contents[0] 
  1. 你要遍歷所有TR的,因此的而不是findAll('tr')findAll('tr')   [0]
  2. 某些行不包含TD,所以我們需要跳過它們,以避免AttributeError的(嘗試刪除這條線)
  3. 如1,要在第一款TD全A,但也 「for td in tr.find」,而不是「 for td in soup.find「,因爲你想查看tr的不在整個文檔中(soup)。
+0

跳過沒有'td'的行的想法非常好。如果該頁面也使用了「tbody」標籤,那會更容易。 –

1

你應該在搜索中更具體些,然後循環遍歷表格行;搶用CSS類,環比除使用切片第一個tr元素的特定表,搶從第一td所有文字:

給割掉第一行
table = soup.find('table', class_='data-table') 
for row in table.find_all('tr')[1:]: 
    print ''.join(row.find('td').stripped_strings) 

或者,你可以跳過thead通過測試指出:

for row in table.find_all('tr'): 
    if row.parent.name == 'thead': 
     continue 
    print ''.join(row.find('td').stripped_strings) 

這本來是更好的四周,如果頁面使用了正確的<tbody>標籤來代替。 :-)

相關問題