gpt4 book ai didi

python - 使用 Python BeautifulSoup 提取 HTML 表

转载 作者:行者123 更新时间:2023-11-30 23:11:30 25 4
gpt4 key购买 nike

我正在尝试从网页中提取表格。下面是使用 beautifulsoup 的 HTML 和 Python 代码。下面的代码总是对我有用,但在这种情况下我会变得空白。提前致谢。

<table>
<thead>
<tr>
<th>Period Ending:</th>
<th class="TalignL">Trend</th>
<th>9/27/2014</th>
<th>9/28/2013</th>
<th>9/29/2012</th>
<th>9/24/2011</th>
</tr>
</thead>
<tr>
<th bgcolor="#E6E6E6">Total Revenue</th>
<td class="td_genTable"><table border="0" align="center" width="*" cellspacing="0" cellpadding="0"><tr><td align="bottom"><table border="0" height="100%" cellspacing="0" cellpadding="0"><tr><td><table cellspacing="0" cellpadding="0" border="0"><tr><td height="15" bgcolor="#47C3D3" width="6"></td><td height="15" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="1" colspan="2" bgcolor="#D1D1D1"></td></tr></table></td><td><table cellspacing="0" cellpadding="0" border="0"><tr><td height="1" bgcolor="#FFFFFF" width="6"></td><td height="1" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="14" bgcolor="#47C3D3" width="6"></td><td height="14" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="1" colspan="2" bgcolor="#D1D1D1"></td></tr></table></td><td><table cellspacing="0" cellpadding="0" border="0"><tr><td height="2" bgcolor="#FFFFFF" width="6"></td><td height="2" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="13" bgcolor="#47C3D3" width="6"></td><td height="13" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="1" colspan="2" bgcolor="#D1D1D1"></td></tr></table></td><td><table cellspacing="0" cellpadding="0" border="0"><tr><td height="7" bgcolor="#FFFFFF" width="6"></td><td height="7" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="8" bgcolor="#47C3D3" width="6"></td><td height="8" bgcolor="#FFFFFF" width="1px"></td></tr><tr><td height="1" colspan="1" bgcolor="#D1D1D1"></td></tr></table></td></tr></table></td></tr></table></td>
<td>$182,795,000</td>
<td>$170,910,000</td>
<td>$156,508,000</td>
<td>$108,249,000</td>
    rows = table.findAll('tr')

for row in rows:
cols = row.findAll('td')
col1 = [ele.text.strip().replace(',','') for ele in cols]

account = col1[0:1]
period1 = col1[2:3]
period2 = col1[3:4]
period3 = col1[4:5]

record = (stock, account,period1,period3,period3)
print record

最佳答案

补充@abarnert 指出的内容。我将获取所有以 $ 开头的 td 元素:

for row in soup.table.find_all('tr', recursive=False):
record = [td.text.replace(",", "") for td in row.find_all("td", text=lambda x: x and x.startswith("$"))]
print record

对于您提供的输入,它会打印:

[u'$182795000', u'$170910000', u'$156508000', u'$108249000']

您可以将其“解压”到单独的变量中:

account, period1, period2, period3 = record

请注意,我显式传递 recursive=False 以避免深入树并仅获取 table 的直接 tr 子级元素。

关于python - 使用 Python BeautifulSoup 提取 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30154377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com