Scrapy Item用法示例(保存item到MySQL数据库,MongoDB数据库,使用官方组件下载图片)
需要学习的地方:
保存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数据库,使用官方组件下载图片)的更多相关文章
- 使用官方组件下载图片,保存到MySQL数据库,保存到MongoDB数据库
需要学习的地方,使用官方组件下载图片的用法,保存item到MySQL数据库 需要提前创建好MySQL数据库,根据item.py文件中的字段信息创建相应的数据表 1.items.py文件 from sc ...
- scrapy爬取数据保存csv、mysql、mongodb、json
目录 前言 Items Pipelines 前言 用Scrapy进行数据的保存进行一个常用的方法进行解析 Items item 是我们保存数据的容器,其类似于 python 中的字典.使用 item ...
- <day001>存储到Mysql、mongoDB数据库+简单的Ajax请求+os模块+进程池+MD5
任务1:记住如何存储到Mysql.mongoDB数据库 ''' 存储到Mysql ''' import pymysql.cursors class QuotePipeline(object): def ...
- Python Json分别存入Mysql、MongoDB数据库,使用Xlwings库转成Excel表格
将电影数据 data.json 数据通过xlwings库转换成excel表格,存入mysql,mongodb数据库中.python基础语法.xlwings库.mysql库.pymongo库.mongo ...
- scrapy基础知识之将item 通过pipeline保存数据到mysql mongoDB:
pipelines.py class xxPipeline(object): def process_item(self, item, spider): con=pymysql.connect(hos ...
- redis数据库到mysql或mongodb数据库
# -*- coding:utf-8 -*-# item_mongodb.py import redis import pymongo import json def main(): redis_co ...
- Scrapy爬去哪儿~上海一日游门票并存入MongoDB数据库
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZwAAAGGCAYAAABPDDfEAAAgAElEQVR4nOy9C3Rb1Z3/+z1Hkm35mT
- Python学习笔记(五)之Python操作Redis、mysql、mongodb数据库
操作数据库 一.数据库 数据库类型主要有关系型数据库和菲关系型数据库. 数据库:用来存储和管理数的仓库,数据库是通过依据“数据结构”将数据格式化,以记录->表->库的关系存储.因此数据查询 ...
- Redis/Mysql/SQLite/MongoDB 数据库对比
一.Redis: redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(so ...
随机推荐
- LeetCode 387. First Unique Character in a String (字符串中的第一个唯一字符)
题目标签:String, HashMap 题目给了我们一个 string,让我们找出 第一个 唯一的 char. 设立一个 hashmap,把 char 当作 key,char 的index 当作va ...
- URAL 1822. Hugo II's War 树的结构+二分
1822. Hugo II's War Time limit: 0.5 second Memory limit: 64 MB The glorious King Hugo II has declare ...
- 模块化开发(二)--- seaJs入门学习
SeaJS是一个基于CMD模块定义规范实现一个模块系统加载器 [CMD规范](https://github.com/cmdjs/specification/blob/master/draft/mo ...
- 【Unity 3D】学习笔记三十六:物理引擎——刚体
物理引擎就是游戏中模拟真是的物理效果.如两个物体发生碰撞,物体自由落体等.在unity中使用的是NVIDIA的physX,它渲染的游戏画面很逼真. 刚体 刚体是一个很很中要的组件. 默认情况下,新创的 ...
- Java 实现简答的单链表的功能
作者:林子木 博客网址:http://blog.csdn.net/wolinxuebin 參考网址:http://blog.csdn.net/sunsaigang/article/details/5 ...
- linux下打开windows txt文件中文乱码问题 (转载)
转自:http://blog.csdn.net/imyang2007/article/details/7448177 在linux操作系统下,我们有时打开在windows下的txt文件,发现在wind ...
- MySQL数据库笔记总结
MySQL数据库总结 一.数据库简介 1. 数据 所谓数据(Data)是指对客观事物进行描述并可以鉴别的符号,这些符号是可识别的.抽象的.它不仅仅指狭义上的数字,而是有多种表现形式:字母.文字.文本. ...
- Linux 命令多到记不住?这个开源项目帮你一网打尽!
本文首发于我的公众号 Linux云计算网络(id: cloud_dev),专注于干货分享,号内有 10T 书籍和视频资源,后台回复「1024」即可领取,欢迎大家关注,二维码文末可以扫. 最近发现了一个 ...
- display:none 和 hidden 区别
- dialog的各类显示方法
图1效果:该效果是当按返回按钮时弹出一个提示,来确保无误操作,采用常见的对话框样式. 代码: 创建对话框方法dialog() protected void dialog() { AlertDialo ...