import urllib.request
import bs4 as bs
sauce = 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]
时,这会产生问题,因为它返回此"IndexError: list index out of range"
。我知道这是因为<th>
属于<tr>
但没有<td>
。
在浏览了 bs4 文档后,我尝试使用 .decompose()
删除<th>
标头,但无济于事。仍生成空列表。如能就此事提供任何帮助,将不胜感激。谢谢。
当它到达空行时,您可以让它跳过,在您的情况下,当您的行返回时[]
for trow in trows:
td = trow.find_all('td')
row = [x.text for x in td]
if row == []:
continue
print(row)
我还要指出,我讨厌尝试通过搜索<table>
、<tr>
、<td>
等来解析表。虽然有时是必要的,但每当我看到<table>
标签时,我都会先尝试熊猫,看看它是否能给我相对想要的东西。我宁愿做一些操作数据帧的工作,而不是通过嵌套标签做很多工作。
import urllib.request
import pandas as pd
sauce = urllib.request.urlopen('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies').read().decode()
tables = pd.read_html(sauce)
因此.read_html()
将返回数据帧列表。在这里的情况下,有 2。因此,要查看它们,只需执行print (tables[0])
或print (tables[1])