【问题标题】:Saving scrapy results into csv file将scrapy结果保存到csv文件中
【发布时间】:2019-03-25 01:56:25
【问题描述】:

我编写的网络爬虫有一些问题。我想保存我获取的数据。如果我从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

【问题讨论】:

    标签: python python-2.7 scrapy web-crawler


    【解决方案1】:

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

    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()
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 1970-01-01
      • 2014-02-20
      • 2011-03-21
      • 1970-01-01
      • 2016-03-02
      • 2016-08-06
      • 1970-01-01
      • 2013-09-30
      相关资源
      最近更新 更多