Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中分隔表中的每个tr?_Python_Html Parsing_Beautifulsoup - Fatal编程技术网

如何在python中分隔表中的每个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

我试图从中解析表,但在管理输出时遇到问题。我只想在输出中显示文本,而且我还想在显示所有td后中断每个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
给你:

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
...