从BeautifulSoup,python中的表(td)中仅提取特定的行和列

时间:2016-03-02 18:21:03

标签: python regex web-scraping beautifulsoup html-table

我想从网站上抓取数据并将其写入CSV。示例代码包含“列名称”和“值”。

<div class="table-responsive">
  <table class="table table-bordered table-hover">
    <tbody>
    <!-- required First 3 column names-->
      <tr>
        <td></td>   
        <td align="center" style="vertical-align:middle;" title=" Number">Number</td>
        <td align="center" style="vertical-align:middle;" colspan="2" title=" Code ">CODE</td>
        <td align="center" style="vertical-align:middle;">Name</td>
        <td align="center" style="vertical-align:middle;" title="Category ">Category</td>
        <td align="center" style="vertical-align:middle;" title="Variation ">Variation</td>
      </tr>
      <!-- required -->
      <tr class="success">
        <td align="center" style="vertical-align:middle;"></td>
        <td align="center" style="vertical-align:middle;"><a href="/Number/3259">3259</a>
        </td>
        <td style="width:125px;height:60px;vertical-align:middle;" <a href="/CODE/ABC123">ABC123</a>
        </td>
        <td align="center" style="vertical-align:middle;"><a title="CODE ABC123" href="/CODE/ABC123">LAND </a>
        </td>
        <td align="center" style="vertical-align:middle;" class="success">3 - Design Reference</td>
        <td align="center" style="vertical-align:middle;" class="success">2 - Production Item</td>
      </tr>
      <!-- not-required -->
      <tr>
        <td colspan="7">
          <div id="BMCRL_36" class="collapse">
            <div class="list-group">
              <a class="list-group-item">
                <h4 class="list-group-item-heading"> Number 3259 - Reference Number ABC123</h4>
                <p class="list-group-item-text"></p>
              </a>
              <a class="list-group-item">
                <h4 class="list-group-item-heading">CODE ABC123 </h4>
                <p class="list-group-item-text"></p>
              </a>
            </div>
          </div>
        </td>
      </tr>
      <!-- required -->
      <tr class="">
        <td align="center" style="vertical-align:middle;"></td>
        <td align="center" style="vertical-align:middle;"><a href="/Number/3260">3260</a>
        </td>
        <td style="width:125px;height:60px;vertical-align:middle;" <a href="/CODE/XYZ453">XYZ453</a>
        </td>
        <td align="center" style="vertical-align:middle;"><a title="CODE XYZ453" href="/CODE/XYZ453">WATER </a>
        </td>
        <td align="center" style="vertical-align:middle;" class="success">3 Control Reference</td>
        <td align="center" style="vertical-align:middle;" class="success">2 Item</td>
      </tr>

    </tbody>
  </table>
</div>
  

输出应该像

  1. 使用此'td'标记时的列名称

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(open('code.html'),'lxml')
    col = soup.find('tr').find_all('td')
    for c in col:
        print(c.get_text())
    

    打印所有列。相反,我只需要,

    ['Number', 'Code', 'Name']

  2. 我不需要'tr',其中包含“colspan”(3rd tr)

  3. 同时删除最后两列值

     tr = soup.findChildren('tr')  
     for t in tr:  
         td = t.findChildren('td')   
         for child in td:   
            print(child.text)
    

    我再次得到包括列和值在内的整个数据,我期待的是

     ['3259', 'ABC123', 'LAND']
               and
     ['3260', 'XYZ453','WATER'] 
    

    删除
         ['3 - Design Reference','2 - Production Item']

2 个答案:

答案 0 :(得分:1)

find_all()的结果切片以仅获取相关的列和单元格。要仅获取相关行,请检查是否存在class属性。

工作样本:

import requests
from bs4 import BeautifulSoup

data = """
your HTML here
"""

soup = BeautifulSoup(data, "lxml")

headers = [c.get_text() for c in soup.find('tr').find_all('td')[1:4]]

data = [[cell.get_text(strip=True) for cell in row.find_all('td')[1:4]]
        for row in soup.find_all("tr", class_=True)]

print(headers)
print(data)

打印:

['Number', 'CODE', 'Name']
[['3259', 'ABC123', 'LAND'], ['3260', 'XYZ453', 'WATER']]

答案 1 :(得分:0)

在Alecxe有用的答案之后,对于更具可读性和Python风格的方法,列表推导可用于排除特定的BS4结果(包括那些不符合设定标准的结果)。 这是一个示例:

rows = [ row for row in soup.findAll('tr') if 'adsbygoogle' not in row.text ]

这将创建一个仅包含必需元素的新行列表。