item pipeline 实例:爬取360摄像图片
生成项目
scrapy startproject image360
cd Image360 && scrapy genspider images images.so.com
一. 构造请求
1. 在setting.py中增加MAX_PAGE=5,表示爬取5页
2. 在images.py中定义start_requests()方法,用来生成5次请求
二. 提取信息
1. 在item.py中定义ImageItem,用于存放需要的数据
2. 在images.py中定义parse函数来提取信息
三. 存储信息
在pipelines.py中定义三个类,来分别实现图片在本地目录,mongodb和mysql中的存储
四. 各文件完整代码如下
1. setting.py文件
# -*- coding: utf- -*- BOT_NAME = 'images360' SPIDER_MODULES = ['images360.spiders']
NEWSPIDER_MODULE = 'images360.spiders' # 设为False才能爬取网站后台数据
ROBOTSTXT_OBEY = False #使pipeline.py中设置生效
ITEM_PIPELINES = {
'images360.pipelines.ImagePipeline': ,
'images360.pipelines.MongoPipeline': ,
'images360.pipelines.MysqlPipeline': ,
} #下载图片后本地存放位置
IMAGES_STORE = './images' #爬5页
MAX_PAGE = #mongodb变量
MONGO_URI = 'localhost'
MONGO_DB = 'images360' #mysql变量
MYSQL_HOST = 'localhost'
MYSQL_DATABASE = 'images360'
MYSQL_USER = 'root'
MYSQL_PASSWORD = ''
MYSQL_PORT =
2. items.py
# -*- coding: utf- -*- # 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): #定义mongodb存储的collection名称和mysql存储的表名称,都定义为images字符串
collection = table = 'images' #定义图片的ID,链接,标题,缩略图
id = Field()
url = Field()
title = Field()
thumb = Field()
3. images.py
# -*- coding: utf- -*-
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(, self.settings.get('MAX_PAGE') + ):
data['sn'] = page *
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
4. . pipelines.py
# -*- coding: utf- -*- # 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('/')[-]
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'])
item pipeline 实例:爬取360摄像图片的更多相关文章
- scrapy爬虫爬取小姐姐图片(不羞涩)
这个爬虫主要学习scrapy的item Pipeline 是时候搬出这张图了: 当我们要使用item Pipeline的时候,要现在settings里面取消这几行的注释 我们可以自定义Item Pip ...
- 第一个nodejs爬虫:爬取豆瓣电影图片
第一个nodejs爬虫:爬取豆瓣电影图片存入本地: 首先在命令行下 npm install request cheerio express -save; 代码: var http = require( ...
- 用scrapy爬取搜狗Lofter图片
用scrapy爬取搜狗Lofter图片 # -*- coding: utf-8 -*- import json import scrapy from scrapy.http import Reques ...
- 用WebCollector爬取站点的图片
用WebCollector爬取整站图片,仅仅须要遍历整站页面.然后将URL为.jpg.gif的页面(文件)保存到本地就可以. 比如我们爬取一个美食站点,获取里面全部的图片: import cn.edu ...
- python 爬虫入门----案例爬取上海租房图片
前言 对于一个net开发这爬虫真真的以前没有写过.这段时间学习python爬虫,今天周末无聊写了一段代码爬取上海租房图片,其实很简短就是利用爬虫的第三方库Requests与BeautifulSoup. ...
- Python-王者荣耀自动刷金币+爬取英雄信息+图片
前提:本文主要功能是 1.用python代刷王者荣耀金币 2.爬取英雄信息 3.爬取王者荣耀图片之类的. (全部免费附加源代码) 思路:第一个功能是在基于去年自动刷跳一跳python代码上面弄的,思路 ...
- 使用Python爬虫爬取网络美女图片
代码地址如下:http://www.demodashi.com/demo/13500.html 准备工作 安装python3.6 略 安装requests库(用于请求静态页面) pip install ...
- 爬虫学习(二)--爬取360应用市场app信息
欢迎加入python学习交流群 667279387 爬虫学习 爬虫学习(一)-爬取电影天堂下载链接 爬虫学习(二)–爬取360应用市场app信息 代码环境:windows10, python 3.5 ...
- Scrapy实战篇(六)之爬取360图片数据和图片
本篇文章我们以360图片为例,介绍scrapy框架的使用以及图片数据的下载. 目标网站:http://images.so.com/z?ch=photography 思路:分析目标网站为ajax加载方式 ...
随机推荐
- Website蝴蝶结构
[Website蝴蝶结构] 网页的其正向链接连结在一起表现为一种蝴蝶结结构. 1.蝴蝶结中部(SCC, Strongly Connected Componnet) 这种网页彼此相连. 2.蝴蝶结左部( ...
- Mac 安装Django
首先 我电脑上的python 是 安装Django 是需要通过 pip 来安装的 最新办的python3.4 应该内置了pip 因此这里 需要下载安装pip pip是常用的Python包管理 ...
- MySQL学习2---索引
MySQL 索引 MySQL索引的建立对于MySQL的高效运行是很重要的,索引可以大大提高MySQL的检索速度. 索引分单列索引和组合索引.单列索引,即一个索引只包含单个列,一个表可以有多个单列索引, ...
- strip命令
去掉文件里调试和符号信息,文件大小变小,一般在发布的时候使用. 主要作用于可执行文件,动态库,目标文件等. 可参考:http://blog.csdn.net/stpeace/article/detai ...
- [Selenium]对于某些对话框即有可能弹出来,也有可能不弹出来,这种应该怎么处理呢?
界面上如果有一个对话框可能弹出来,也可能不弹出,我们都要认为是正常,应该怎么处理呢? /** * check if release notes dialog present * @author j * ...
- 【新手指南】App原型设计:如何快速实现这6种交互效果?
做App原型设计,那么页面切换.进度条.页面滚动.图片轮播,下拉菜单,搜索框这些交互效果必不可少.如何简单快速地实现这些效果呢?以下小编根据经验为大家提供了一些简单的设计方法,以供参考. 1.页面跳转 ...
- Python中where()函数的用法
where()的用法 首先强调一下,where()函数对于不同的输入,返回的只是不同的. 1当数组是一维数组时,返回的值是一维的索引,所以只有一组索引数组 2当数组是二维数组时,满足条件的数组值返回的 ...
- Web挖掘
Web挖掘 Web挖掘的目标是从Web的超链接.网页内容和使用日志中探寻有用的信息.依据Web挖掘任务,可以划分为三种主要类型:Web结构挖掘.Web内容挖掘和Web使用挖掘.Web结构挖掘简单的说就 ...
- linux 查找php.ini在那个文件夹
第一种方法:通过phpinfo查看 第二种方法: 执行 php -i | grep php.ini 结果如下:
- PHP中刷新输出缓冲详解[转载]
PHP中刷新输出缓冲详解 分类: PHP Web开发2011-07-23 17:42 1795人阅读 评论(0) 收藏 举报 phpbuffer浏览器outputapache模块脚本 buffer是一 ...