gpt4 book ai didi

python - 使用 Python 和 Beautifulsoup 如何在 div 中选择所需的表?

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

我希望能够选择包含“应付帐款”文本的表格,但我没有得到任何我正在尝试的东西,我几乎在猜测使用 findall。谁能告诉我该怎么做?

例如,这就是我的开头:

<div>
<tr>
<td class="lft lm">Accounts Payable
</td>
<td class="r">222.82</td>
<td class="r">92.54</td>
<td class="r">100.34</td>
<td class="r rm">99.95</td>
</tr>
<tr>
<td class="lft lm">Accrued Expenses
</td>
<td class="r">36.49</td>
<td class="r">33.39</td>
<td class="r">31.39</td>
<td class="r rm">36.47</td>
</tr>
</div>

这就是我想要得到的结果:

<tr>
<td class="lft lm">Accounts Payable
</td>
<td class="r">222.82</td>
<td class="r">92.54</td>
<td class="r">100.34</td>
<td class="r rm">99.95</td>
</tr>

最佳答案

您可以选择 lft lm 类的 td 元素,然后检查 element.string 以确定您是否有“应付账款”td:

import sys
from BeautifulSoup import BeautifulSoup

# where so_soup.txt is your html
f = open ("so_soup.txt", "r")
data = f.readlines ()
f.close ()

soup = BeautifulSoup ("".join (data))

cells = soup.findAll('td', {"class" : "lft lm"})
for cell in cells:
# You can compare cell.string against "Accounts Payable"
print (cell.string)

例如,如果您想检查以下兄弟的应付帐款,您可以使用以下内容:

if (cell.string.strip () == "Accounts Payable"):
sibling = cell.findNextSibling ()
while (sibling):
print ("\t" + sibling.string)
sibling = sibling.findNextSibling ()

编辑更新

如果你想打印出原始的 HTML,只是为了 Accounts Payable 元素之后的 sibling ,这是为此的代码:

lines = ["<tr>"]
for cell in cells:
lines.append (cell.prettify().decode('ascii'))
if (cell.string.strip () == "Accounts Payable"):
sibling = cell.findNextSibling ()
while (sibling):
lines.append (sibling.prettify().decode('ascii'))
sibling = sibling.findNextSibling ()
lines.append ("</tr>")

f = open ("so_soup_out.txt", "wt")
f.writelines (lines)
f.close ()

关于python - 使用 Python 和 Beautifulsoup 如何在 div 中选择所需的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6194240/

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