【问题标题】:Using Python and Beautifulsoup how do I select the desired table in a div?使用 Python 和 Beautifulsoup 如何在 div 中选择所需的表?
【发布时间】:2011-05-31 22:21:02
【问题描述】:

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

【问题讨论】:

  • 如果对我的解决方案有任何具体问题,请告诉我。

标签: python html-parsing beautifulsoup


【解决方案1】:

您可以选择 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,只针对 应付帐款 元素之后的兄弟姐妹,代码如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 2021-08-02
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多