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加载方式 ...
随机推荐
- Linux centos下php安装cphalcon扩展的方法
说明: 操作系统:CentOS php安装目录:/usr/local/php php.ini配置文件路径:/usr/local/php/etc/php.ini 1.安装cphalcon cd /usr ...
- 【BZOJ3489】A simple rmq problem【kd树】
题意 给出一个长度为n的序列,给出M个询问:在[l,r]之间找到一个在这个区间里只出现过一次的数,并且要求找的这个数尽可能大.如果找不到这样的数,则直接输出0.我会采取一些措施强制在线. 分析 预处理 ...
- DropDownList绑定数据的几种方式
1. 视图中添加可以直接通过单击属性"Items"后的按钮为某一DropDownList控件添加数据项.每添加一项数据就是添加了一个ListItem(列表控件中的数据项).这种方式 ...
- MongoDB C# 驱动教程
C# 驱动版本 v1.6.x 本教程基于C#驱动 v1.6.x . Api 文档见此处: http://api.mongodb.org/csharp/current/. 简介 本教程介绍由10gen支 ...
- 链表求和12 · Add Two Numbers
反向存储,从左往右加 [抄题]: 你有两个用链表代表的整数,其中每个节点包含一个数字.数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头.写出一个函数将两个整数相加,用链表形式返回和.给 ...
- 因式分解 · Factor Combinations
[抄题]: 给出 n = 8 返回 [[2,2,2],[2,4]] // 8 = 2 x 2 x 2 = 2 x 4 [暴力解法]: 时间分析: 空间分析: [思维问题]: [一句话思路]: 类似于全 ...
- 优化 resolv.conf
DNS lookup 在把域名解析成 IP 过程中耽误了不少时间,尤其是访问比较复杂的网站的时候,比如某个页面包含多个 url,一次请求需要做多次 DNS 解析,并且从用户浏览器到 DNS serve ...
- [Python]利用type()动态创建类
Python作为动态语言,可以动态地创建函数和类定义.比如说定义一个Hello类,就写一个hello.py模块: #! /usr/bin/env python #coding=utf-8 class ...
- dedecms分页
mshd_orderlist.php $page = isset($_REQUEST[; $count = $mshd_miaosha_member_obj -> getMemberList(t ...
- http头部信息
1.常见的返回码 100: 请服务器端继续返回 200:成功 301:永久重定向 存的地址永久的改变了 301 302 : 暂时重定向 302仍然使用老得url 401 : 无法找到资源file n ...