0

我有这样的 HTML 文本

  <tr>
    <td><strong>Turnover</strong></td>
          <td width="20%" class="currency">&pound;348,191</td>
              <td width="20%" class="currency">&pound;856,723</td>
              <td width="20%" class="currency">&pound;482,177</td>
          </tr>
  <tr>
    <td>&nbsp;&nbsp;Cost of sales</td>
          <td width="20%" class="currency">&pound;275,708</td>
              <td width="20%" class="currency">&pound;671,345</td>
              <td width="20%" class="currency">&pound;357,587</td>
          </tr>
  <tr>

在它之前和之后有很多html。我想解析数字。可以有不同数量的td列,所以我想解析所有列。在这种情况下,有三列,所以我正在寻找的结果是:

[348191, 856723, 482177]

理想情况下,我想将TurnoverCost of Sales数据分别解析为不同的变量

4

1 回答 1

5

您可以使用BeautifulSoup

>>> from bs4 import BeautifulSoup as BS
>>> html = """  <tr>
...     <td><strong>Turnover</strong></td>
...           <td width="20%" class="currency">&pound;348,191</td>
...               <td width="20%" class="currency">&pound;856,723</td>
...               <td width="20%" class="currency">&pound;482,177</td>
...           </tr>
...   <tr>
...     <td>&nbsp;&nbsp;Cost of sales</td>
...           <td width="20%" class="currency">&pound;275,708</td>
...               <td width="20%" class="currency">&pound;671,345</td>
...               <td width="20%" class="currency">&pound;357,587</td>
...           </tr>"""
>>> soup = BS(html)
>>> for i in soup.find_all('tr'):
...     if i.find('td').text == "Turnover":
...             for x in i.find_all('td', {'class':'currency'}):
...                     print x.text
...
£348,191
£856,723
£482,177

解释

首先,我们将 HTML 转换为bs4我们可以轻松浏览的类型。find_all,猜猜它的作用没有奖品,找到所有<tr>s.

我们遍历每个 tr,如果第一个<td>是 Turnover,那么我们将遍历其余的<td>s.

我们遍历每个tdwithclass="currency"并打印其内容。

于 2013-06-17T12:23:54.967 回答