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 ...
随机推荐
- 2-sat总结
算法 构造一个有向图G,每个变量xi拆成两个点2i和2i+1 分别表示xi为假,xi为真 那么对于“xi为真或xj为假”这样的条件 我们就需要连接两条边 2*i —>2*j(表示如果i为假,那么 ...
- Makefile 实际用例分析(二) ------- 比较通用的一种架构
之前已经讲了这一篇文章:Makefile实际用例分析(一)-----比较通用的一种架构 现在这篇其实和那个差的不是很多,只是在布局上有些差别(这个makefile也是论坛上一起讨论过的,囧,忘了哪个论 ...
- 编译android4.4 报错error: call to '__property_get_too_small_error' declared with attribute 的处理 (转载)
转自:http://blog.csdn.net/syhost/article/details/14448899 完整的报错为: system/core/include/cutils/propertie ...
- poj1200Crazy Search(hash)
题目大意 将一个字符串分成长度为N的字串.且不同的字符不会超过NC个.问总共有多少个不同的子串. /* 字符串hash O(n)枚举起点 然后O(1)查询子串hash值 然后O(n)找不一样的个数 ...
- Tyvj1305最大子序和(单调队列优化dp)
描述 输入一个长度为n的整数序列,从中找出一段不超过M的连续子序列,使得整个序列的和最大. 例如 1,-3,5,1,-2,3 当m=4时,S=5+1-2+3=7当m=2或m=3时,S=5+1=6 输入 ...
- CentOS 7.0 firewall防火墙关闭firewall作为防火墙,这里改为iptables防火墙
CentOS 7.0默认使用的是firewall作为防火墙,这里改为iptables防火墙步骤: 1.先检查是否安装了: iptables service iptables status 2.安装ip ...
- viewDidUnload,viewDidLoad,viewWillAppear,viewWillDisappear的作用以及区别
viewDidLoad:在视图加载后被调用 viewWillAppear:视图即将可见时调用.默认情况下不执行任何操作 viewDidAppear: 视图已完全过渡到屏幕上时调用 viewWillDi ...
- Sqoop 是什么?(二)
Sqoop 是传统数据库与 Hadoop 之间数据同步的工具,它是 Hadoop 发展到一定程度的必然产物,它主要解决的是传统数据库和Hadoop之间数据的迁移问题.Sqoop 是连接传统关系型数据库 ...
- Mysql的事务、视图、索引、备份和恢复
事务 事务是作为单个逻辑工作单元执行的一系列操作,一个逻辑工作单元必须具备四个属性.即:原子性.一致性.隔离性.持久性,这些特性通常简称为ACID. 原子性(Atomicity) 事务是不可分割的 ...
- Java中的异常注意点
在java中 使用throw关键字抛出异常 使用throws关键字声明异常 public static void main(String[] args) throws Exception{ ...