2014-05-24 2 views
1

http://www.livescore.co.uk/worldcup/tables/.I에서 테이블을 구문 분석하려고합니다. 출력을 관리하는 데 문제가 있습니다. 출력에 텍스트 만 표시하고 싶습니다. 또한 모든 td가 표시된 후 각 tr을 마주 치고 싶습니다. 초보자이고 오전입니다. 배울 려구. 누구든지 내가 뭘 잘못하고 있는지 제안 할 수있어. 어떤 제안이 있니?파이썬의 테이블에서 각 tr을 어떻게 분리합니까?

from BeautifulSoup import BeautifulSoup 
import urllib2 

pageSource=urllib2.urlopen('http://www.livescore.com/worldcup/tables/').read() 

soup = BeautifulSoup(pageSource) 
alltables = soup.findAll("table", {"class":"league-wc table bh"}) 
results=[] 
for table in alltables: 
    rows = table.findAll('tr') 
    lines=[] 
    for tr in rows[1:]: 
     cols = tr.findAll('td') 
     for td in cols: 

      text=td.renderContents().strip('\n') 

      lines.append(text) 




    text_table='\n'.join(lines) 
    print text_table 

출력 :

<a href="/worldcup/team-brazil/">Brazil</a> 
0 
0 
0 
0 
0 
0 
0 
0 
1 
<a href="/worldcup/team-cameroon/">Cameroon</a> 
0 
0 
0 
0 
0 
0 
0 
0 
1 
<a href="/worldcup/team-croatia/">Croatia</a> 
0 
0 
0 
0 
0 
0 
0 
0 
1 
<a href="/worldcup/team-mexico/">Mexico</a> 
0 
0 
0 
0 
0 
0 
0 
0 
....similar 

내 욕망 출력 : 여기

1,brazil,0,0,0,0,0,0,0,0,0,0 
2,cameroon,0,0,0,0,0,0,0,0,0,0 
3,craotia,0,0,0,0,0,0,0,0,0,0 
4,Meico,0,0,0,0,0,0,0,0,0,0 

답변

0

당신이가는 :

from BeautifulSoup import BeautifulSoup 
import urllib2 

pageSource=urllib2.urlopen('http://www.livescore.com/worldcup/tables/').read() 

soup = BeautifulSoup(pageSource) 
alltables = soup.findAll("table", {"class":"league-wc table bh"}) 

results=[] 
for table in alltables: 
    rows = table.findAll('tr') 
    _table = [] 
    for tr in rows[1:]: 
     _row = [] 
     cols = tr.findAll('td') 
     for td in cols: 
      if td.findAll('a'): 
       text=td.a.renderContents().strip() 
      else: 
       text=td.renderContents().strip() 
      _row.append(text) 
     _table.append(_row) 
    results.append(_table) 


# print results 
index = 1 
for table in results: 
    for row in table: 
     print ','.join([str(index)] + row[1:]) 
     index += 1 

출력 :

1,Brazil,0,0,0,0,0,0,0,0 
2,Cameroon,0,0,0,0,0,0,0,0 
3,Croatia,0,0,0,0,0,0,0,0 
4,Mexico,0,0,0,0,0,0,0,0 
5,Australia,0,0,0,0,0,0,0,0 
6,Chile,0,0,0,0,0,0,0,0 
... 

아이디어는 원시 데이터를 먼저 수집 한 다음 논리를 작성하여 데이터를 표시합니다 (어떤 방식 으로든).

+0

도움을 주셔서 감사합니다. – Avinash

+0

@ user3606884 문제가 해결되면 답변을 수락 한 것으로 표시하십시오.) – mitnk

관련 문제