使用官方组件下载图片,保存到MySQL数据库,保存到MongoDB数据库
需要学习的地方,使用官方组件下载图片的用法,保存item到MySQL数据库
需要提前创建好MySQL数据库,根据item.py文件中的字段信息创建相应的数据表
1.items.py文件
from scrapy import Item,Field class Images360Item(Item):
# MongoDB数据库的表名和MySQL数据库的表名
collection = table = 'images'
id = Field()
url = Field()
title = Field()
thumb = Field()
2.settings.py文件
ITEM_PIPELINES = {
'images360.pipelines.ImagesPipeline': 300,
'images360.pipelines.MongoPipeline': 301,
'images360.pipelines.MySQLPipeline': 302,
}
# MongoDB数据库参数
MONGO_URI = '127.0.0.1'
MONGO_DATABASE = 'images360'
# 图片保存路径
IMAGES_STORE = 'D:\\images360\\images'
# MySQL数据库参数
MYSQL_HOST = '127.0.0.1'
MYSQL_DATABASE = 'images360'
MYSQL_USER = 'root'
MYSQL_PASSWORD = 'root'
MYSQL_PORT = 3306

3.pipeline.py文件
import pymongo
import pymysql
from scrapy import Request
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline # 下载项目图片
class ImagesPipeline(ImagesPipeline):
def file_path(self, request, response=None, info=None):
url = request.url
filename = url.split('/')[-1]
return filename 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']) # 保存到MongoDB数据库
class MongoPipeline(object):
# 数据表名
collection_name = 'scrapy_items' def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db @classmethod
# 从settings.py文件中获取参数
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DATABASE', 'items') # 数据库名
) def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db] def close_spider(self, spider):
self.client.close() def process_item(self, item, spider):
self.db[item.collection].insert_one(dict(item)) # 从items.py文件中获取表名
return item # 保存数据到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())
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


使用官方组件下载图片,保存到MySQL数据库,保存到MongoDB数据库的更多相关文章
- Scrapy Item用法示例(保存item到MySQL数据库,MongoDB数据库,使用官方组件下载图片)
需要学习的地方: 保存item到MySQL数据库,MongoDB数据库,下载图片 1.爬虫文件images.py # -*- coding: utf-8 -*- from scrapy import ...
- mysql数据库和mongodb数据库的相关操作以及两个数据库的区别
在docs命令中执行数据操作 MySQL数据库 先启动MySQL服务器 net start mysql 进入MySQL服务器MySQL -uroot -p(这里写你的数据库密码) (-P是从哪个端口 ...
- php将图片以二进制保存到mysql数据库并显示
一.存储图片的数据表结构: -- -- 表的结构 `image` -- CREATE TABLE IF NOT EXISTS `image` ( `id` int(3) NOT NULL AUTO_I ...
- Python实现将图片以二进制格式保存到MySQL数据库中,以及取出:
创建数据库表格式: CREATE TABLE photo ( photo_no int(6) unsigned NOT NULL auto_increment, image MEDIUMBLOB, P ...
- Unity WWW下载图片并保存到Unity的Assets下
1.新建一个UGUI的Image. 2.新建一个脚本wwwTest.cs: using System.Collections; using System.Collections.Generic; us ...
- 爬取伯乐在线文章(四)将爬取结果保存到MySQL
Item Pipeline 当Item在Spider中被收集之后,它将会被传递到Item Pipeline,这些Item Pipeline组件按定义的顺序处理Item. 每个Item Pipeline ...
- 微信昵称有特殊符号怎么保存到mysql库里?
微信昵称有特殊符号怎么保存到mysql库里? mysql库怎么保存emoji表情? 这里提供 1 种稳妥有效的方法: // 入库之前,使用 Base64 编码 String nickname = re ...
- Asp.net Session 保存到MySql中
一 网站项目引入"mysql.web.dll" 二 web.config配置中添加mysql数据库连接字符串 <connectionStrings> <remov ...
- pandas对象保存到mysql出错提示“BLOB/TEXT column used in key specification without a key length”解决办法
问题 将DataFrame数据保存到mysql中时,出现错误提示: BLOB/TEXT column used in key specification without a key length 原因 ...
随机推荐
- torch lua tips
1.luarocks 离线安装Moses 下载 Moses-Moses-1.6.1-1.zip cd Moses-Moses-1.6.1-1 Moses-Moses-1.6.1-1# luarocks ...
- java多线程——竞态条件与临界区 学习笔记
允许被多个线程同时执行的代码称作线程安全的代码.线程安全的代码不包含竞态条件.当多个线程同时更新共享资源时会引发竞态条件.因此,了解 Java 线程执行时共享了什么资源很重要. 一.局部变量(函数内定 ...
- 【Codevs1288】埃及分数
Position: http://codevs.cn/problem/1288/ Description 在古埃及,人们使用单位分数的和(形如1/a的, a是自然数)表示一切有理数. 如:2/3=1/ ...
- 71.Ext.form.ComboBox 完整属性
转自:https://blog.csdn.net/taotaoqi/article/details/7409514 Ext.form.ComboBox 类全称: Ext.form.ComboBox 继 ...
- Android之NDK开发(转载)
http://www.cnblogs.com/devinzhang/archive/2012/02/29/2373729.html 一.NDK产生的背景 Android平台从诞生起,就已经支持C.C+ ...
- 9.22 NOIP模拟题
吉林省信息学奥赛 2017 冬令营 ...
- phpStorm更新后配置svn无法使用
phpStorm迎来新的更新,结果之前配置的svn竟然无法使用啦,快捷键一类也没有作用.各种查找解决方案,最后找到解决方案.点击File找到Settings,找到Plugins这个部分,这个部分是管理 ...
- 关于MVC视图下拉菜单绑定与取值的问题
绑定视图中dropdownlist: 视图中的代码: @Html.DropDownList("select1") 此处的slect1也就是页面上的<select>< ...
- MyBatis分页组件--PageHelper
一.介绍 PageHelper是国内非常优秀的一款开源的 mybatis 分页插件,它支持基本主流与常用的数据库,例如 Oracle.Mysql.MariaDB.SQLite.Hsqldb 等. 官网 ...
- 属性字符串(NSAttributedString)的简单应用
属性字符串NSAttributedString 可以对字符串附加格式信息,由于对于对不同文本片段使用不同的格式,属性字符串类特别合适. IOS 6中对样式文本有了大改善,大部分主要的UIKit控件都允 ...