2015-10-04 69 views
1

試圖編寫一些代碼,首先用他的salary.request來匹配玩家的名字。我可以這樣寫,以便通過從班級「sortcell」中調用它來獲取給定團隊中的每個玩家的名字,但我似乎無法弄清楚如何獲得薪水,因爲他們都被叫了出來。用BeautifulSoup抓取某個​​類

from bs4 import BeautifulSoup 
from urllib import urlopen 

teams = ['http://espn.go.com/nba/team/roster/_/name/atl/atlanta-hawks'] 

for team in teams: 
    html = urlopen('' + team) 
    soup = BeautifulSoup(html.read(), 'lxml') 
    names = soup.findAll("td", {"class": "sortcell"}) 
    salary = soup.findAll("td", {"class": "td"}) 
    print(salary) 
    for i in range(1, 15): 
     name = names[i].get_text() 
     print(name) 

您可以在以'salary'開頭的代碼中看到我的(失敗)嘗試。關於如何抓取薪水類的任何想法?謝謝!

預期的行爲:

工資變量應返回的工資對於一個給定的球員,但目前沒有返回。

回答

3

您的salary列表爲空,因爲帶薪資信息的<td>元素沒有CSS類;當然不是td

如果您從names單元導航到相應的薪資單元,您將會有更輕鬆的時間;該行中的最後一個:

for name in soup.find_all("td", class_="sortcell"): 
    salary = name.parent.find_all('td')[-1] # last cell in the row 
    print(name.get_text()) 
    print(salary.get_text()) 

我使用了soup.find_all()語法; findAll()是該方法的舊BeautifulSoup 3名稱,該名稱已被棄用。

+0

這樣做的另一種方式不是找到sortcell類,然後找到它的父類。你也可以這樣做''用於soup.find_all中的播放器(「tr」,{「class」:re.compile('^ player- \ d + - \ d +')}):print(player.find_all(「td 「)[ - 1] .get_text())'。這是自上而下的解決方案。但Martijn Pieters解決方案更好,imo。 – colidyre

+0

太棒了!就像一個魅力@馬特金!非常感謝! – n1c9

相關問題