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

2024-04-29 03:00:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够选择包含“应付帐款”文本的表,但我没有得到任何我正在尝试的东西,我几乎是猜测使用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>

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

^{pr2}$

Tags: rm文本divtrclasstdlmaccounts
1条回答
网友
1楼 · 发布于 2024-04-29 03:00:58

可以使用classlft lm选择td元素,然后检查元素.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)

例如,如果您想检查以下同级帐户的应付帐款,可以使用以下方法:

^{pr2}$

更新以进行编辑

如果您想打印出原始HTML,只针对Accounts payment元素后的同级文件,则以下代码为:

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 ()

相关问题 更多 >