Scrapy(1) 爬取起点中文网小说,并保存到数据库 |
您所在的位置:网站首页 › Python爬取数据存入MySQL能更新吗 › Scrapy(1) 爬取起点中文网小说,并保存到数据库 |
爬取起点中文网小说
Scrapy框架结构
引擎(ENGINE)调度器(SCHEDULER)下载器(DOWNLOADER)爬虫(SPIDERS)项目管道(ITEM PIPELINES)下载器中间件(Downloader Middlewares)爬虫中间件(Spider Middlewares)
需求分析
目标网站 https://www.qidian.com/rank/hotsales?style=1&page=1 提取内容为:小说名称、作者、类型和形式 创建项目,在命令行定位到放项目的目录 scrapy startproject qidian_hot打开pycharm pipelines.py添加代码 import pymongo class MongoDBPipeline(object): def open_spider(self, spider): # 在spider开始之前,调用一次 host = spider.settings.get("MONGODB_HOST", "localhost") port = spider.settings.get("MONGODB_PORT", 27017) db_name = spider.settings.get("MONGODB_NAME", "qidian") collection_name = spider.settings.get("MONGODB_COLLECTION", "hot") self.db_client = pymongo.MongoClient(host=host, port=port) # 客户端对象 # 指定数据库 self.db = self.db_client[db_name] # 指定集合 self.db_collection = self.db[collection_name] def process_item(self, item, spider): # 处理每一个item item_dict = dict(item) self.db_collection.insert_one(item_dict) def close_spider(self, spider): # 在spider结束时,调用一次 self.db_client.close()打开start.py,运行,打开 MongoDB compass 查看 《从零开始学Scrapy网络爬虫》,这本书挺不错的,有原理,有源码,有视频,还有ppt |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |