Joh*_*acs 15 python pipeline web-crawler scrapy
我需要保存一个文件(.pdf),但我不确定该怎么做.我需要保存.pdfs并以这样的方式存储它们,使它们组织在一个目录中,就像它们存储在我正在抓取它们的网站上一样.
从我可以收集到的东西,我需要建立一个管道,但从我理解的管道保存"项目"和"项目"只是基本数据,如字符串/数字.保存文件是否正确使用管道,或者我应该将文件保存在蜘蛛中?
Rol*_*Max 15
是和否[1].如果您获取pdf,它将存储在内存中,但如果pdf不够大,无法填满可用内存,那么就可以了.
您可以将pdf保存在蜘蛛回调中:
def parse_listing(self, response):
# ... extract pdf urls
for url in pdf_urls:
yield Request(url, callback=self.save_pdf)
def save_pdf(self, response):
path = self.get_path(response.url)
with open(path, "wb") as f:
f.write(response.body)
Run Code Online (Sandbox Code Playgroud)
如果您选择在管道中执行此操作:
# in the spider
def parse_pdf(self, response):
i = MyItem()
i['body'] = response.body
i['url'] = response.url
# you can add more metadata to the item
return i
# in your pipeline
def process_item(self, item, spider):
path = self.get_path(item['url'])
with open(path, "wb") as f:
f.write(item['body'])
# remove body and add path as reference
del item['body']
item['path'] = path
# let item be processed by other pipelines. ie. db store
return item
Run Code Online (Sandbox Code Playgroud)
[1]另一种方法可能只存储pdfs的url并使用另一个进程来获取文档而不缓冲到内存中.(例如wget
)
您可以直接使用FilesPipeline,假设您已经拥有文件网址,该链接显示了如何使用FilesPipeline:
https://groups.google.com/forum/print/msg/scrapy-users/kzGHFjXywuY/O6PIhoT3thsJ