@staticmethod asyncdefsaveData(data): logging.info('saving data %s', data) if data: returnawait collection.update_one({ 'id': data.get('id') }, { '$set': data }, upsert=True)
asyncdefmain(self): # todo 设置任务 # 从这一步的话可以拿到指定页数的列表 scrape_index_tasks = [asyncio.ensure_future(self.scrapeIndex(page)) for page inrange(1, PAGE_NUMBER + 1)] results = await asyncio.gather(*scrape_index_tasks) # 使用gather而不是wait # todo 拿到每一页中的ids # 这一步就是从预览大概到每一页中获取详细信息 for index_data in results: ifnot index_data: continue for item in index_data.get('results'): # 使用字典的get方法 self.ids.append(item.get('id')) # todo 根据拿到的id进入协程同步进行拿到想要的结果并存入 scrape_detail_tasks = [asyncio.ensure_future(self.scrapeDetail(each)) for each in self.ids] await asyncio.wait(scrape_detail_tasks) # todo 最后关闭session会话 await self.session.close()