scrapy 跨组件传递参数

启动框架开始爬取目标网页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

阅读 4.5k
2 个回答

个人觉得有两种方法:
一是在spider模块中,将你需要的collection_name定义为全局变量,然后在pipelines模块中导入过来.
二是可以在item中增加一个collection_name字段,在pipelines中使用 item.pop('collection_name')弹出来即可

新手上路,请多包涵

引用 @玉帛 的方法,可以解决问题,实现“从MongoDB读取start_url,对start_url进行处理,生成特征值,再将特征值传递给pipeline作为collection表名”的操作,具体解决方案如下。

Spider中:

def start_requests(self):
    client = pymongo.MongoClient('localhost',27017)
    db_name = 'Sina'
    db = client[db_name]
    collection_set01 = db['UrlsQueue']
    datas=list(collection_set01.find({},{'_id':0,'url':1,'status':1}))
    for data in datas:
        if data.get('status') == 'pending':
            url=data.get('url')
            pattern='(?<=/)([0-9a-zA-Z]{9})(?=\?)'
            if re.search(pattern,url):
                collection_name=re.search(pattern,url).group(0)
            start_url='https://weibo.cn/comment/'+collection_name+'?ckAll=1'
            collection_set01.update({'url':url},{'$set':{'status':'proccessing'}})                
            break
        else:
            pass
    client.close()
    yield Request(url=start_url,callback=self.parse, cookies=cookie, meta={'collection_name':collection_name})

从数据库中获取start_url,提取特征值,并对其处理,带meta参数发送request

def parse(self,response):
        collection_name=response.meta['collection_name']
        ......
        for i in range(0,len(node)):
            item['collection_name']=collection_name
            yield item
            

parse()从response中解析数据的同时提取回传的meta参数

Pipeline中:

def close_spider(self, spider):
    self.db['UrlsQueue'].update({'status':'proccessing'},{'$set':{'status':'finished'}})
    self.client.close()

def process_item(self, item, spider):
    self.collection_name=item.pop('collection_name')
    self.db[self.collection_name].insert_one(dict(item))
    return item

pop掉collection_name参数即可

非常感谢 @玉帛 的帮助

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题