python - 将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
解决方案
如果你查看蜘蛛的输出,你会看到一堆错误信息,像这样被记录:
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 或Item
s,而不是您正在创建的单项元组。
像这样简单的东西应该可以工作:
yield {
'name': response.xpath("normalize-space(//h2[@class='rgs'])").get(),
'phone': response.xpath("//span[@itemprop='telephone']/text()").get()
}
推荐阅读
- reactjs - 执行上下文不会像通常那样从 getStaticPaths 移动到 getStaticProps
- sql-server - 用 WITH 选择
- javascript - 如何切换布尔特定状态?
- amazon-web-services - Quicksight Embedded:使用我的 react + django App 评估技术可行性
- reactjs - 反应原生文本不更新
- c# - 应用客户端投影后无法翻译集合操作
- bash - 对参数定义的 JSON 进行 PUT 调用
- python-3.x - Python:禁用和重新启用按钮
- visual-studio-code - 如何在 VSCode 中将 nvim 选择发送到终端
- aws-lambda - 如何让 AWS API Gateway 和 Lambda REST API 正确处理 POST 作为 application/x-www-form-urlencoded