import urllib.requestimport bs4 as bssauce = urllib.request.urlopen('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies').read().decode()soup = bs.BeautifulSoup(sauce, 'lxml')soup.th.decompose()table = soup.find('table')trows = soup.find_all('tr')for trow in trows: td = trow.find_all('td') row = [x.text for x in td] print(row)我一直在玩抓取網(wǎng)頁和表格似乎是最難的。但是,我能夠很好地創(chuàng)建表數(shù)據(jù)的行列表。問題是有一個由于表頭而打印的空白列表<th>。當(dāng)我只想打印row[0]并且row[1]因為它返回 this時,這會產(chǎn)生問題"IndexError: list index out of range"。我知道這是因為<th>屬于<tr>但沒有<td>.在查看了 bs4 文檔后,我嘗試使用.decompose()刪除<th>標(biāo)題無濟于事。仍然會生成一個空列表。對此事的任何幫助將不勝感激。謝謝你。
添加回答
舉報
0/150
提交
取消