scrapy - 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"> </div> <div class="zoekres"> <h4>Aantal kindplaatsen</h4> <div class="paratable"> <table cellpadding="0" cellspacing="0"> <tr> <th> </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"> </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
解决方案
一种可能的方式:
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
推荐阅读
- c++ - 如何打印当前执行文件 C++ 的内容?
- r - rvest 返回 schannel:SNI 或证书检查失败:SEC_E_WRONG_PRINCIPAL (0x80090322) - 目标主体名称不正确
- c# - 试图构建一个数据库查找应用程序,但我得到'实体类型......需要定义一个主键',尽管它是在我的数据库中定义的
- django - FieldError:无法将关键字“username_iexact”解析为字段
- javascript - javascript推入后如何返回数组
- java - 在每行之后打印二维数组中行的总和
- html - 固定导航栏上不同层的 Z-index CSS 问题
- javascript - CloneNode Vs Clone 我们必须将其设为子节点吗?
- ubuntu - 为什么 coturn 服务器返回 401:未经授权
- python - 如何更改菜单中特定操作的样式?