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)我一直在玩抓取网页和表格似乎是最难的。但是,我能够很好地创建表数据的行列表。问题是有一个由于表头而打印的空白列表<th>。当我只想打印row[0]并且row[1]因为它返回 this时,这会产生问题"IndexError: list index out of range"。我知道这是因为<th>属于<tr>但没有<td>.在查看了 bs4 文档后,我尝试使用.decompose()删除<th>标题无济于事。仍然会生成一个空列表。对此事的任何帮助将不胜感激。谢谢你。
添加回答
举报
0/150
提交
取消