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加载方式 ...
随机推荐
- ubuntu ibus&language 启动失败
[ubuntu ibus&language 启动失败] 版本:ubuntu 10.04 现像:language support & ibus 无法启动,导致无法使用中文输入法 原因:l ...
- Inception
http://baijiahao.baidu.com/s?id=1601882944953788623&wfr=spider&for=pc
- 106. Construct Binary Tree from Inorder and Postorder Traversal (Tree; DFS)
Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume tha ...
- Putty建立隧道的方法[z]
通过上节我们了解了SSH隧道的优点,但是无论是现实中还是网络中,隧道都是有入口和出口的,本节就以Putty隧道为例,详细介绍Putty建立隧道的方法. 模拟案例一: 端口,出口为2012端口,隧道建立 ...
- 斜杠反斜杠,去空格\xa0,连接函数join()
1斜杠反斜杠 斜杠:/.反斜杠:\. 反斜杠\,在windows系统中用来表示目录. 而在unix系统中,/表示目录.由于web遵循unix命名,所以在网址(URL)中,/表示目录. 在unix系统中 ...
- Redis通用命令(七)
Keys的通用操作: (1)获得所有的keyskeys *(2)查看my开头的keykeys my?(3)删除keydel key1 key2(4)key是否存在exists key1 exists ...
- Oracle物化视图的一般使用
普通视图和物化视图根本就不是一个东西,说区别都是硬拼到一起的,首先明白基本概念,普通视图是不存储任何数据的,他只有定义,在查询中是转换为对应的定义SQL去查询,而物化视图是将数据转换为一个表,实际存储 ...
- StarUML 5.0问题解决:Failed to open the model file. Invalid file format.
使用StarUML 5.0打开一个已有的文件时,如果遇到报"Failed to open the model file. Invalid file format."错误,则原因可能 ...
- Ubuntu的常识使用了解2
1. 在linux系统中,所有的目录(分区)都是挂靠在/跟目录下. 使用「cd」这个指令来切換目录.切换目录的方式:(1)绝对路径,以根目录做开头/, (2)相对目录, 没有以根目录开头. 注意:插补 ...
- 企业搜索引擎开发之连接器connector(十九)
连接器是基于http协议通过推模式(push)向数据接收服务端推送数据,即xmlfeed格式数据(xml格式),其发送数据接口命名为Pusher Pusher接口定义了与发送数据相关的方法 publi ...