启动框架开始爬取目标网页start_url之后,需要从start_url这个字符串中提取一个特征值,作为MongoDB数据库的collection名,再通过pipeline将item存储。
大致流程:
根据框架流程来看是可以实现的,spider的处理在pipeline之前
pipeline中相关代码:
import pymongo
class MongoPipeline(object):
#collection_name = 'Gsl6RoxfN'
def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db
@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
)
def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db]
def close_spider(self, spider):
self.client.close()
def process_item(self, item, spider):
self.db[self.collection_name].insert_one(dict(item))
return item
现在的问题就是如何将spider中的变量collection_name传递到pipeline中
感谢阅读提问
Thanks in advance
个人觉得有两种方法:
一是在spider模块中,将你需要的collection_name定义为全局变量,然后在pipelines模块中导入过来.
二是可以在item中增加一个collection_name字段,在pipelines中使用 item.pop('collection_name')弹出来即可