1、先打開(kāi)settting.py的item_pipeline(原來(lái)處于注釋狀態(tài))
ITEM_PIPELINES = {
'moon_blog.pipelines.MoonBlogPipeline': 300,
}
2且警、在pipeline.py文件中寫入
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os
import csv
class MoonBlogPipeline(object):
def __init__(self):
# csv文件的位置,無(wú)需事先創(chuàng)建
store_file = os.path.dirname(__file__) + '/spiders/articles.csv'
print("***************************************************************")
# 打開(kāi)(創(chuàng)建)文件
self.file = open(store_file, 'a+', encoding="utf-8",newline='')
# csv寫法
self.writer = csv.writer(self.file, dialect="excel")
def process_item(self, item, spider):
# 判斷字段值不為空再寫入文件
print("正在寫入......")
if item['article_title']:
# 主要是解決存入csv文件時(shí)出現(xiàn)的每一個(gè)字以‘惑惶,’隔離
self.writer.writerow([item['article_title'],item['article_link'],item['publish_date'],item['scan_num'],item['article_content']])
return item
def close_spider(self, spider):
# 關(guān)閉爬蟲時(shí)順便將文件保存退出
self.file.close()
注:如何解決存入csv文件時(shí)出現(xiàn)的每一個(gè)字以‘武花,’隔離的問(wèn)題。
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者