【问题标题】:Scrapy - how can I split the data in this table?Scrapy - 如何拆分此表中的数据?
【发布时间】:2017-10-17 12:22:00
【问题描述】:

我正在尝试从表中抓取数据,但是,表数据似乎具有相同的 xpath。这是表格的示例 - http://www.hpft.nhs.uk/services/find-our-services/hertfordshire/cheshunt

当我使用response.xpath('//td/text()').extract() 时,它会返回整个表格。

我想也许我可以使用绝对 xpath,例如response.xpath('//tr/td[3]/text()').extract() 在示例中返回 ['01992 818600', '01707 364012', '01707 364003'] - 从理论上讲,它应该在整个站点的所有表中是动态的?

但是,我想做的是在我的输出 csv 文件中将每个表条目的服务、地址和电话添加为单独的行。但我不知道如何拆分我的回复返回的列表数据?我已经设置了我想要使用的项目。

【问题讨论】:

    标签: python python-3.x xpath web-scraping scrapy


    【解决方案1】:

    您应该遍历表格行,然后将各个字段收集到项目中:

    for row in response.xpath('//table[@class="map"]//tr[position() > 1]'):
        item = dict()
        item['service'] = row.xpath('./td[1]/text()').extract_first()
        item['address'] = ' '.join(x.strip() for x in row.xpath('./td[2]/text()').extract())
        item['phone'] = row.xpath('./td[3]/text()').extract_first()
        yield item
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 2013-02-05
      • 2021-08-11
      • 2023-02-01
      相关资源
      最近更新 更多