【问题标题】:When saving scraped item and file, Scrapy inserts empty lines in output csv file保存抓取的项目和文件时,Scrapy 在输出 csv 文件中插入空行
【发布时间】:2016-01-12 14:18:49
【问题描述】:

我有 Scrapy(1.0.3 版)蜘蛛,我从网页中提取一些数据并下载文件,如下所示(简化):

def extract_data(self, response):
    title = response.xpath('//html/head/title/text()').extract()[0].strip()
    my_item = MyItem()
    my_item['title'] = title    

    file_url = response.xpath('...get url of file...')
    file_urls = [file_url]  # here there can be more urls, so I'm storing like a list
    fi = FileItem()
    fi['file_urls'] = file_urls 
    yield my_item
    yield fi

在 pipelines.py 中我只是重写 FilePipeline 来更改文件名:

from scrapy.pipelines.files import FilesPipeline

class CustomFilesPipeline(FilesPipeline):
    def file_path(self, request, response=None, info=None):
        filename = format_filename(request.url)
        return filename

在 items.py 我有:

class MyItem(scrapy.Item):
    title = scrapy.Field()

class FileItem(scrapy.Item):
    file_urls = scrapy.Field()
    files = scrapy.Field()

在 settings.py 我有:

ITEM_PIPELINES = {
    'myscraping.pipelines.CustomFilesPipeline': 100
} 

现在在输出 csv 文件中我得到如下内容:

title1
title2
,
,
title3
etc.

看起来空行(只有逗号)代表下载的文件,我想知道或获得建议如何防止这些行出现在输出 csv 文件中。 (文件保存在文件夹中)。
在 Scrapy 设置中,我发现了 FEED_STORE_EMPTY(默认情况下为 false,即它不应导出空提要),但这与我猜的文件无关。
我觉得这与管道有关,但我不知道该怎么做。
任何帮助将不胜感激

【问题讨论】:

  • 为什么不把file_urls放到你的item MyItem()中,只产生一种item?
  • 太棒了!!!我从来没有想过这一点(不知何故我在文档中忽略了):) 非常感谢

标签: python scrapy scrapy-spider scrapy-pipeline


【解决方案1】:

我把答案贴在这里:

def extract_data(自我,响应): title = response.xpath('//html/head/title/text()').extract()[0].strip() 我的项目 = 我的项目() my_item['title'] = 标题 file_url = response.xpath('...获取文件的 url...') my_item['file_urls'] = [file_url] 产生 my_item

【讨论】:

    猜你喜欢
    • 2014-02-28
    • 2013-07-04
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2022-11-25
    相关资源
    最近更新 更多