首页 > 解决方案 > Scrapy - 从表中提取数据

问题描述

我正在尝试将表中的数据提取到 CSV 文件的单独字段中。

网站中的表格如下所示:

表格图像

并且(部分)网页的来源如下所示:

    <div id="right">
      <div id="rightwrap">
        <h1>Krimpen aan den IJssel</h1>
        <div class="tools">
          <a href="javascript:;" onclick="window.print();" class="print">print</a>
          <a href="../p49dda187ba43e/capaciteit-per-gemeente.html">terug</a>
        </div>
        <h2 class="lijst">Krimpen aan den IJssel</h2>
        <div class="dotted">&nbsp;</div>
        <div class="zoekres">
          <h4>Aantal kindplaatsen</h4>
          <div class="paratable">
            <table cellpadding="0" cellspacing="0">
              <tr>
                <th>&nbsp;</th>
                <th>2006</th>
                <th>2008</th>
                <th>2009</th>
                <th>2010</th>
                <th>2011</th>
              </tr>
              <tr>
                <th>KDV</th>
                <td>144</td>
                <td>144</td>
                <td>174</td>
                <td>243</td>
                <td>-</td>
              </tr>
              <tr>
                <th>BSO</th>
                <td>135</td>
                <td>265</td>
                <td>315</td>
                <td>365</td>
                <td>-</td>
              </tr>
              <tr>
                <th>Totaal</th>
                <td>279</td>
                <td>409</td>
                <td>489</td>
                <td>608</td>
                <td>-</td>
              </tr>
            </table>
          </div>
        </div>
      </div>
    </div>
    <div class="brtotal">&nbsp;</div>
  </div>

我设法使用以下代码检索了“Krimpen aan den IJssel”地点的名称:

   def parse(self, response):   
            item = OrderedDict()
            for col in self.cols:
                item[col] = 'None'
            item['Gemeente'] = response.css('h2.lijst::text').get('') 
            yield item

但我无法检索本网站表格中显示的值。使用表的标准方法:

 response.xpath('//*[@class="table paratable"]

似乎不起作用,或者我没有足够的经验来正确设置参数。谁能向我提供一些代码行,将这个表中的值带入我的 CSV 文件的以下列

KDV_2006 KDV_2008 KDV_2009 KDV_2010 KDV_2011 BSO_2006 BSO_2008
BSO_2009 BSO_2010 BSO_2011

标签: scrapy

解决方案


一种可能的方式:

result = {}
years = response.xpath('//div[@class="paratable"]/table/tr[1]/th[position() > 1]/text()').getall()
for row in response.xpath('//div[@class="paratable"]/table/tr[position() > 1][position() < last()]'):
    field_name = row.xpath('./th/text()').get()
    values = row.xpath('./td/text()').getall()
    for year, value in zip(years, values):
        result[f'{field_name}_{year}'] = value

推荐阅读