小编典典

如何使用BeautifulSoup成对提取表数据?

python

我的数据样本:

<table id = "history">
<tr class = "printCol">
<td class="name">Google</td><td class="date">07/11/2001</td><td class="state">
<span>CA</span>
</td>
</tr>
<tr class = "printCol">
<td class="name">Apple</td><td class="date">27/08/2001</td>
</tr>
<tr class = "printCol">
<td class="name">Microsoft</td><td class="date">01/11/1991</td>
</tr>
</table>

Beautifulsoup代码:

table = soup.find("table", id = "history")

rows = table.findAll('tr')
for tr in rows:
    cols = tr.findAll('td')
    for td in cols:
        print td.find(text=True)

MySQL存储的所需输出(列表):

['Google|07/11/2001|CA', 'Apple|27/08/2001', 'Microsoft|01/11/1991']

我的输出(难以将正确的日期与正确的公司相关联):

Google
07/11/2001


Apple
27/08/2001
Microsoft
01/11/1991

我编写了一个从每个 tr中 提取元素的函数,但我认为在原始的 for
循环中有一种更有效的方法来完成所有操作。我想将它们作为数据对存储在列表中。有什么想法吗?


阅读 225

收藏
2021-01-20

共1个答案

小编典典

列表理解将使它更容易:

table = soup.find("table", id = "history")
rows = table.findAll('tr')
data = [[td.findChildren(text=True) for td in tr.findAll("td")] for tr in rows]
# data now contains:
[[u'Google', u'07/11/2001'],
 [u'Apple', u'27/08/2001'],
 [u'Microsoft', u'01/11/1991']]

# If the data may contain extraneous whitespace you can clean it up
# Additional processing could also be done - but once you hit much more
# complex than this later maintainers, yourself included, will thank you
# for using a series of for loops that call clearly named functions to perform
# the work.
data = [[u"".join(d).strip() for d in l] for l in data]

# If you want to store it joined as name | company
# then simply follow that up with:
data = [u"|".join(d) for d in data]

列表理解基本上是一个for带有聚合的反向循环:

[[td.findNext(text=True) for td in tr.findAll("td")] for tr in rows]

转换为 *

final_list = []
intermediate_list = []

for tr in rows:
    for td in tr.findAll("td")
        intermediate_list.append(td.findNext(text=True))

    final_list.append(intermediate_list)
    intermediate_list = []

data = final_list

* 粗略地讲-我们不考虑生成器 而不 建立中间列表的麻烦,因为我现在不能在不弄乱示例的情况下添加生成器。

2021-01-20