首页 > 解决方案 > 将scrapy结果保存到csv文件中

问题描述

我写的网络爬虫有一些问题。我想保存我获取的数据。如果我从scrapy教程中理解正确,我只需要放弃它,然后使用scrapy crawl <crawler> -o file.csv -t csv正确的启动爬虫?由于某种原因,该文件仍然是空的。这是我的代码:

# -*- coding: utf-8 -*-
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class PaginebiancheSpider(CrawlSpider):
name = 'paginebianche'
allowed_domains = ['paginebianche.it']
start_urls = ['https://www.paginebianche.it/aziende-clienti/lombardia/milano/comuni.htm']

rules = (
    Rule(LinkExtractor(allow=(), restrict_css = ('.seo-list-name','.seo-list-name-up')),
         callback = "parse_item",
         follow = True),)

def parse_item(self, response):
    if(response.xpath("//h2[@class='rgs']//strong//text()") != [] and response.xpath("//span[@class='value'][@itemprop='telephone']//text()") != []):
        yield ' '.join(response.xpath("//h2[@class='rgs']//strong//text()").extract()) + " " + response.xpath("//span[@class='value'][@itemprop='telephone']//text()").extract()[0].strip(),

我正在使用 python 2.7

标签: pythonpython-2.7scrapyweb-crawler

解决方案


如果你查看蜘蛛的输出,你会看到一堆错误信息,像这样被记录:

2018-10-20 13:47:52 [scrapy.core.scraper] ERROR: Spider must return Request, BaseItem, dict or None, got 'tuple' in <GET https://www.paginebianche.it/lombardia/abbiategrasso/vivai-padovani.html>

这意味着您没有产生正确的东西 - 您需要 dicts 或Items,而不是您正在创建的单项元组。
像这样简单的东西应该可以工作:

yield {
    'name': response.xpath("normalize-space(//h2[@class='rgs'])").get(),
    'phone': response.xpath("//span[@itemprop='telephone']/text()").get()
}

推荐阅读