需要学习的地方:

保存item到MySQL数据库,MongoDB数据库,下载图片

1.爬虫文件images.py

# -*- coding: utf-8 -*-
from scrapy import Spider, Request
from urllib.parse import urlencode
import json from images360.items import ImageItem class ImagesSpider(Spider):
name = 'images'
allowed_domains = ['images.so.com']
start_urls = ['http://images.so.com/'] def start_requests(self):
data = {'ch': 'photography', 'listtype': 'new'}
base_url = 'https://image.so.com/zj?'
for page in range(1, self.settings.get('MAX_PAGE') + 1):
data['sn'] = page * 30
params = urlencode(data)
url = base_url + params
yield Request(url, self.parse) def parse(self, response):
result = json.loads(response.text)
for image in result.get('list'):
item = ImageItem()
item['id'] = image.get('imageid')
item['url'] = image.get('qhimg_url')
item['title'] = image.get('group_title')
item['thumb'] = image.get('qhimg_thumb_url')
yield item

2.items.py

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html from scrapy import Item, Field class ImageItem(Item):
collection = table = 'images' id = Field()
url = Field()
title = Field()
thumb = Field()

3.pipelines.py

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://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 MongoPipeline(object):
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_DB')
) def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db] def process_item(self, item, spider):
name = item.collection
self.db[name].insert(dict(item))
return item def close_spider(self, spider):
self.client.close() class MysqlPipeline():
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):
print(item['title'])
data = dict(item)
keys = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data))
sql = 'insert into %s (%s) values (%s)' % (item.table, keys, values)
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 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'])

4.settings.py

配置文件中增加如下内容

ITEM_PIPELINES = {
'images360.pipelines.ImagePipeline': 300,
'images360.pipelines.MongoPipeline': 301,
'images360.pipelines.MysqlPipeline': 302,
} IMAGES_STORE = './images' MAX_PAGE = 50 MONGO_URI = 'localhost'
MONGO_DB = 'images360' MYSQL_HOST = 'localhost'
MYSQL_DATABASE = 'images360'
MYSQL_USER = 'root'
MYSQL_PASSWORD = ''
MYSQL_PORT = 3306

代码下载地址:https://files.cnblogs.com/files/sanduzxcvbnm/Images360-master.7z

Scrapy Item用法示例(保存item到MySQL数据库,MongoDB数据库,使用官方组件下载图片)的更多相关文章

  1. 使用官方组件下载图片,保存到MySQL数据库,保存到MongoDB数据库

    需要学习的地方,使用官方组件下载图片的用法,保存item到MySQL数据库 需要提前创建好MySQL数据库,根据item.py文件中的字段信息创建相应的数据表 1.items.py文件 from sc ...

  2. scrapy爬取数据保存csv、mysql、mongodb、json

    目录 前言 Items Pipelines 前言 用Scrapy进行数据的保存进行一个常用的方法进行解析 Items item 是我们保存数据的容器,其类似于 python 中的字典.使用 item ...

  3. <day001>存储到Mysql、mongoDB数据库+简单的Ajax请求+os模块+进程池+MD5

    任务1:记住如何存储到Mysql.mongoDB数据库 ''' 存储到Mysql ''' import pymysql.cursors class QuotePipeline(object): def ...

  4. Python Json分别存入Mysql、MongoDB数据库,使用Xlwings库转成Excel表格

    将电影数据 data.json 数据通过xlwings库转换成excel表格,存入mysql,mongodb数据库中.python基础语法.xlwings库.mysql库.pymongo库.mongo ...

  5. scrapy基础知识之将item 通过pipeline保存数据到mysql mongoDB:

    pipelines.py class xxPipeline(object): def process_item(self, item, spider): con=pymysql.connect(hos ...

  6. redis数据库到mysql或mongodb数据库

    # -*- coding:utf-8 -*-# item_mongodb.py import redis import pymongo import json def main(): redis_co ...

  7. Scrapy爬去哪儿~上海一日游门票并存入MongoDB数据库

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZwAAAGGCAYAAABPDDfEAAAgAElEQVR4nOy9C3Rb1Z3/+z1Hkm35mT

  8. Python学习笔记(五)之Python操作Redis、mysql、mongodb数据库

    操作数据库 一.数据库 数据库类型主要有关系型数据库和菲关系型数据库. 数据库:用来存储和管理数的仓库,数据库是通过依据“数据结构”将数据格式化,以记录->表->库的关系存储.因此数据查询 ...

  9. Redis/Mysql/SQLite/MongoDB 数据库对比

    一.Redis: redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(so ...

随机推荐

  1. 李洪强经典面试题30-iOS应用性能调优的25个建议和技巧

    iOS应用性能调优的25个建议和技巧 本文来自iOS Tutorial Team 的 Marcelo Fabri,他是Movile的一名 iOS 程序员.这是他的个人网站:http://www.mar ...

  2. kafka01

    消息队列松耦合 消息队列

  3. 洛谷 P3377 模板左偏树

    题目:https://www.luogu.org/problemnew/show/P3377 左偏树的模板题: 加深了我对空 merge 的理解: 结构体的编号就是原序列的位置. 代码如下: #inc ...

  4. C++11 function使用

    function是一组函数对象包装类的模板,实现了一个泛型的回调机制. 引入头文件 #include <functional>using namespace std;using names ...

  5. PCB genesis大孔加小孔(即卸力孔)实现方法

    一.为什么 大孔中要加小孔(即卸力孔) 这其实跟钻刀的排屑有关了,当钻刀越大孔,排屑量也越大(当然这也得跟转速,下刀速的参数有关系),通常当钻刀越大,转速越慢,下刀速也越慢(因为要保证它的排屑通畅). ...

  6. thinkphp调试手段

    使用ThinkPHP应该掌握的调试手段经常看到有人问到findAll的返回数据类型是什么之类的问题,以及出错了不知道什么原因的情况,其实还是没有熟悉ThinkPHP内置的调试手段和方法,抛开IDE本身 ...

  7. 9.10NOIP模拟题

      9.10 NOIP模拟赛 题目名称 区间 种类 风见幽香 题目类型 传统 传统 传统 可执行文件名 section kinds yuuka 输入文件名 section.in kinds.in yu ...

  8. promise 小抄

    catch的用法 我们知道Promise对象除了then方法,还有一个catch方法,它是做什么用的呢?其实它和then的第二个参数一样,用来指定reject的回调,用法是这样: getNumber( ...

  9. 去掉myeclipse的预览窗口

    1,选择菜单: windows -> preferences2,在弹出窗口中选择General-> Editors -> FileAssociations3,在上方框内选择*.jsp ...

  10. 354 Russian Doll Envelopes 俄罗斯娃娃信封

    You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envel ...