了解pipeline.py
pipeline类参数解释:
class SomethingPipeline(object):
def __init__(self):
# 可选实现,做参数初始化等
# 写入你的业务逻辑
def process_item(self, item, spider):
# item (Item 对象) – 爬取数据的item
# spider (Spider 对象) – 爬取该item的spider
# 这个方法必须实现,每个item pipeline组件都需要调用该方法,
# 这个方法必须返回一个 Item 对象,被丢弃的item将不会被之后的pipeline组件所处理。
return item
def open_spider(self, spider):
# spider (Spider 对象) – 被开启的spider
# 可选实现,spider开启时,这个方法被调用。
def close_spider(self, spider):
# spider (Spider 对象) – 被关闭的spider
# 可选实现,spider关闭时,这个方法被调用
修改pipeline.py
根据各个参数需要修改pipeline函数后,达成应有的输出效果
class YoutubespiderPipeline(object):
def __init__(self):
"""
Define the CSVItemExporter for the YouTubeDataModel.
Item Exportation, file encoding and the sequence of fields defined.
"""
self.csv_exporter = CsvItemExporter(open('data-master.csv', 'wb'))
self.csv_exporter.encoding = 'utf-8'
self.csv_exporter.fields_to_export = ['url', 'title'
, 'views', 'likes', 'dislikes'
, 'channel_name', 'publish_date'
, 'channel_subscriber_count']
self.csv_exporter.start_exporting()
def spider_closed(self, spider):
self.csv_exporter.finish_exporting()
def process_item(self, item, spider):
"""
Exports item through Item Exporter
:param item: containing the data
:param spider: spider that extracted and saved inside item
:return: the item itself
"""
self.csv_exporter.export_item(item)
return item