scrapy save mysql or mongo, 和圖片下載儲存

來源:互聯網
上載者:User

標籤:mysq   %s   lin   false   下載   password   rdo   ble   dia   

# -*- coding: utf-8 -*-# Define your item pipelines here## Don‘t forget to add your pipeline to the ITEM_PIPELINES setting# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.htmlimport pymongoimport pymysqlfrom scrapy import Requestfrom scrapy.exceptions import DropItemfrom scrapy.pipelines.images import ImagesPipelineclass Images360Pipeline(object):    def process_item(self, item, spider):        return item# mongo dbclass MongoPipeline(object):    def __init__(self, mongo_url, mongo_db):        self.mongo_url = mongo_url        self.mongo_db = mongo_db    @classmethod    def from_crawler(cls, crawler):        return cls(            mongo_url=crawler.settings.get(‘MONGO_URL‘),            mongo_db=crawler.settings.get(‘MONGO_DB‘)        )    def open_spider(self, spider):        self.client = pymongo.MongoClient(self.mongo_url)        self.db = self.client[self.mongo_db]    def process_item(self, item, spider):        self.db[item.collection].insert(dict(item))        return item    def close_spider(self, spider):        self.client.close()# mysqlclass MysqlPipeline(object):    def __init__(self, host, database, user, password, port):        self.host = host        self.database = database        self.user = user        self.password = password        self.port = port    @classmethod    def from_crawler(cls, crawler):        return cls(            host=crawler.settings.get(‘MYSQL_HOST‘),            database=crawler.settings.get(‘MYSQL_DATABASE‘),            user=crawler.settings.get(‘MYSQL_USER‘),            password=crawler.settings.get(‘MYSQL_PASSWORD‘),            port=crawler.settings.get(‘MYSQL_PORT‘)        )    def open_spider(self, spider):        self.db = pymysql.connect(self.host, self.user, self.password, self.database, charset=‘utf8‘, port=self.port)        self.cursor = self.db.cursor()    def close_spider(self, spider):        self.db.close()    def process_item(self, item, spider):        data = dict(item)        keys = ‘,‘.join(data.keys())        value = ‘,‘.join([‘%s‘] * len(data))        sql = ‘insert into %s (%s) values (%s)‘ % (item.table, keys, value)        self.cursor.execute(sql, tuple(data.values()))        self.db.commit()        return item# 下載圖片class ImagePipeline(ImagesPipeline):    def file_path(self, request, response=None, info=None):        url = request.url        file_name = url.split(‘/‘)[-1]        return file_name    # 如果圖片下載失敗,不進行儲存資料庫,IMAGES_STORE = ‘儲存的檔案名稱如: ./images‘    def item_completed(self, results, item, info):        image_paths = [x[‘path‘] for ok, x in results if ok]        if not image_paths:            raise DropItem(‘Image Downloaded Failed‘)        return item    def get_media_requests(self, item, info):        yield Request(item[‘url‘])

settings.py配置

# 只列出部分代碼,最先執行ImagePipelineITEM_PIPELINES = {    ‘images360.pipelines.ImagePipeline‘: 300,    ‘images360.pipelines.MongoPipeline‘: 301,    ‘images360.pipelines.MysqlPipeline‘: 302,}MAX_PAGE = 50MONGO_URL = ‘localhost‘MONGO_DB = ‘images360‘BOT_NAME = ‘images360‘MYSQL_HOST = ‘localhost‘MYSQL_DATABASE = ‘images360‘MYSQL_USER = ‘root‘MYSQL_PASSWORD = ‘123456‘MYSQL_PORT = ‘3306‘# 下載的圖片儲存路徑IMAGE_STORE = ‘./images‘SPIDER_MODULES = [‘images360.spiders‘]NEWSPIDER_MODULE = ‘images360.spiders‘# Crawl responsibly by identifying yourself (and your website) on the user-agent# USER_AGENT = ‘images360 (+http://www.yourdomain.com)‘# Obey robots.txt rulesROBOTSTXT_OBEY = False

  

scrapy save mysql or mongo, 和圖片下載儲存

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.