scrapy save mysql or mongo, 和图片下载保存

# -*- 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.html
import pymongo
import pymysql
from scrapy import Request
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline

class Images360Pipeline(object):
    def process_item(self, item, spider):
        return item

# mongo db
class 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()

# mysql
class 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配置

# 只列出部分代码,最先执行ImagePipeline

ITEM_PIPELINES = {
    ‘images360.pipelines.ImagePipeline‘: 300,
    ‘images360.pipelines.MongoPipeline‘: 301,
    ‘images360.pipelines.MysqlPipeline‘: 302,
}

MAX_PAGE = 50
MONGO_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 rules
ROBOTSTXT_OBEY = False

  

原文地址:https://www.cnblogs.com/412013cl/p/9098739.html

时间: 2024-07-31 03:18:39

scrapy save mysql or mongo, 和图片下载保存的相关文章

Scrapy基础————图片下载后将本地路径添加到Item中

前边讲到简单的图片下载,但是怎样将图片的本地路径和存储在Item中的数据对应起来,所以本篇博文讲解到如何将 本地的下载后的图片路径写入到Item中 思路:自定义pipline,多加个管道,该管道继承下载图片的类,并重写与Item 交互的方法,从众提取到本地路径,并返回这个Item交给下一个pipline管道 具体代码: 先导入 from scrapy.pipelines.images import ImagesPipeline 1 #补充Item的字段,将文章列表页的图片下载下来,并将图片的路径

(8)分布式下的爬虫Scrapy应该如何做-图片下载(源码放送)

  转载主注明出处:http://www.cnblogs.com/codefish/p/4968260.html 在爬虫中,我们遇到比较多需求就是文件下载以及图片下载,在其它的语言或者框架中,我们可能在经过数据筛选,然后异步的使用文件下载类来达到目的,Scrapy框架中本身已经实现了文件及图片下载的文件,相当的方便,只要几行代码,就可以轻松的搞定下载.下面我将演示如何使用scrapy下载豆瓣的相册首页内容. 优点介绍: 1)自动去重 2)异步操作,不会阻塞 3)可以生成指定尺寸的缩略图 4)计算

Scrapy图片下载,自定义图片名字

学习Scrapy过程中发现用Scrapy下载图片时,总是以他们的URL的SHA1 hash值为文件名,如: 图片URL:http://www.example.com/image.jpg 它的SHA1 hash值为:3afec3b4765f8f0a07b78f98c07b83f013567a0a 则下载的图片为:3afec3b4765f8f0a07b78f98c07b83f013567a0a.jpg 目的是下载的图片为:image.jpg或者xxx.jpg 可以通过编写Pipeline来实现. 以

爬虫 Scrapy框架 爬取图虫图片并下载

items.py,根据需求确定自己的数据要求 1 # -*- coding: utf-8 -*- 2 3 # Define here the models for your scraped items 4 # 5 # See documentation in: 6 # https://doc.scrapy.org/en/latest/topics/items.html 7 8 import scrapy 9 10 11 class TodayScrapyItem(scrapy.Item): 12

scrapy框架来爬取壁纸网站并将图片下载到本地文件中

首先需要确定要爬取的内容,所以第一步就应该是要确定要爬的字段: 首先去items中确定要爬的内容 class MeizhuoItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() # 图集的标题 title = scrapy.Field() # 图片的url,需要来进行图片的抓取 url = scrapy.Field() pass 在确定完要爬的字段之后,就是分析网站页面的请求

下载远程(第三方服务器)文件、图片,保存到本地(服务器)的方法、保存抓取远程文件、图片

将一台服务器的文件.图片,保存(下载)到另外一台服务器进行保存的方法: 1 #region 图片下载 2 3 #region 图片下载[使用流.WebRequest进行保存] 4 /// <summary> 5 /// 图片下载[使用流.WebRequest进行保存] 6 /// </summary> 7 /// <param name="fileUrl">图片URL地址(例如:http://img.baidu.com/video/img/video

从网络下载图片,保存,并用UIImageView从保存中显示

代码: - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(50, 100, 200, 200)]; img.backgroundColor=[UIColor redColor]; [self.view addSubview:img]; /

详细讲解Android的图片下载框架UniversialImageLoader之磁盘缓存(一)

沉浸在Android的开发世界中有一些年头的猴子们,估计都能够深深的体会到Android中的图片下载.展示.缓存一直是心中抹不去的痛.鄙人亦是如此.Ok,闲话不说,为了督促自己的学习,下面就逐一的挖掘Android中还算是比较牛叉的图片处理框架UniversialImageLoader以飨读者吧! 凡事如果过于草率必将陷入泥塘不能自拔.还是按部就班的一步一步的将这个框架给啃透. 第一个要讲的是磁盘的缓存的接口DiskCache 首先看一下其中的核心的接口的代码: File getDirector

python scrapy爬取皇冠体育源码下载网站数据二(scrapy使用详细介绍)

1.scrapy工程创建皇冠体育源码下载论坛:haozbbs.com Q1446595067 在命令行输入如下命令,创建一个使用scrapy框架的工程 scrapy startproject scrapyDemo 1 命令创建好后的工程结构如下图scrapy工程结构 输入如下命令,在工程目录中创建示例代码 PS C:\ProjectPycharm> cd scrapyDemoPS C:\ProjectPycharm\scrapyDemo> scrapy genspider example ex