zde*_*ulo 5 python scrapy scrapy-spider scrapy-pipeline
我有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
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
在items.py我有:
class MyItem(scrapy.Item):
title = scrapy.Field()
class FileItem(scrapy.Item):
file_urls = scrapy.Field()
files = scrapy.Field()
Run Code Online (Sandbox Code Playgroud)
在settings.py我有:
ITEM_PIPELINES = {
'myscraping.pipelines.CustomFilesPipeline': 100
}
Run Code Online (Sandbox Code Playgroud)
现在在输出csv文件中我得到这样的东西:
title1
title2
,
,
title3
etc.
Run Code Online (Sandbox Code Playgroud)
它看起来像空行(只有逗号)代表下载文件,我想知道或得到如何防止这些行在输出csv文件中的建议.(文件保存到文件夹中).
在Scrapy设置中,我发现了FEED_STORE_EMPTY(默认为false,即它不应导出空的feed),但这与我猜的文件无关.
我觉得这必须与管道有关,但我无法弄清楚如何做到这一点.
任何帮助,将不胜感激
我把答案贴在这里:
def extract_data(自身,响应):
title = response.xpath('//html/head/title/text()').extract()[0].strip()
我的项目 = 我的项目()
my_item['标题'] = 标题
file_url = response.xpath('...获取文件的 url...')
my_item['file_urls'] = [file_url]
产生我的项目