如何在python中分隔表中的每个tr?
我试图从中解析表,但在管理输出时遇到问题。我只想在输出中显示文本,而且我还想在显示所有td后中断每个tr。我是初学者,我正在努力学习。所以有人能建议我做错了什么。有什么建议吗如何在python中分隔表中的每个tr?,python,html-parsing,beautifulsoup,Python,Html Parsing,Beautifulsoup,我试图从中解析表,但在管理输出时遇到问题。我只想在输出中显示文本,而且我还想在显示所有td后中断每个tr。我是初学者,我正在努力学习。所以有人能建议我做错了什么。有什么建议吗 from BeautifulSoup import BeautifulSoup import urllib2 pageSource=urllib2.urlopen('http://www.livescore.com/worldcup/tables/').read() soup = BeautifulSoup(pageS
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
给你:
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
...
想法是先收集原始数据,然后编写逻辑来显示数据(以任何方式)。非常感谢您的帮助。
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
...