使用scrapy ImagesPipeline爬取图片资源的示例代码
作者:大囚长 发布时间:2023-07-07 13:46:05
标签:scrapy,ImagesPipeline,爬取
这是一个使用scrapy的ImagesPipeline爬取下载图片的示例,生成的图片保存在爬虫的full文件夹里。
scrapy startproject DoubanImgs
cd DoubanImgs
scrapy genspider download_douban douban.com
vim spiders/download_douban.py
# coding=utf-8
from scrapy.spiders import Spider
import re
from scrapy import Request
from ..items import DoubanImgsItem
class download_douban(Spider):
name = 'download_douban'
default_headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, sdch, br',
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Host': 'www.douban.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
}
def __init__(self, url='1638835355', *args, **kwargs):
self.allowed_domains = ['douban.com']
self.start_urls = []
for i in xrange(23):
if i == 0:
page_url = 'http://www.douban.com/photos/album/' + url
else:
page_url = 'http://www.douban.com/photos/album/' + url + '/?start=' + str(i*18)
self.start_urls.append(page_url)
self.url = url
# call the father base function
# super(download_douban, self).__init__(*args, **kwargs)
def start_requests(self):
for url in self.start_urls:
yield Request(url=url, headers=self.default_headers, callback=self.parse)
def parse(self, response):
list_imgs = response.xpath('//div[@class="photolst clearfix"]//img/@src').extract()
if list_imgs:
item = DoubanImgsItem()
item['image_urls'] = list_imgs
yield item
vim settings.py
# -*- coding: utf-8 -*-
# Scrapy settings for DoubanImgs project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'DoubanImgs'
SPIDER_MODULES = ['DoubanImgs.spiders']
NEWSPIDER_MODULE = 'DoubanImgs.spiders'
ITEM_PIPELINES = {
'DoubanImgs.pipelines.DoubanImgDownloadPipeline': 300,
}
IMAGES_STORE = '.'
IMAGES_EXPIRES = 90
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'DoubanImgs (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 0.5
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'DoubanImgs.middlewares.DoubanimgsSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'DoubanImgs.middlewares.DoubanimgsDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'DoubanImgs.pipelines.DoubanimgsPipeline': 300,
#}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
vim items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy import Field
class DoubanImgsItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
image_urls = Field()
images = Field()
image_paths = Field()
vim 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
from scrapy.pipelines.images import ImagesPipeline
from scrapy.exceptions import DropItem
from scrapy import Request
from scrapy import log
class DoubanImgsPipeline(object):
def process_item(self, item, spider):
return item
class DoubanImgDownloadPipeline(ImagesPipeline):
default_headers = {
'accept': 'image/webp,image/*,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, sdch, br',
'accept-language': 'zh-CN,zh;q=0.8,en;q=0.6',
'cookie': 'bid=yQdC/AzTaCw',
'referer': 'https://www.douban.com/photos/photo/2370443040/',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
}
def get_media_requests(self, item, info):
for image_url in item['image_urls']:
self.default_headers['referer'] = image_url
yield Request(image_url, headers=self.default_headers)
def item_completed(self, results, item, info):
image_paths = [x['path'] for ok, x in results if ok]
if not image_paths:
raise DropItem("Item contains no images")
item['image_paths'] = image_paths
return item
来源:https://blog.csdn.net/Jailman/article/details/79170849


猜你喜欢
- 本文实例为大家分享了Python基于Socket实现简单聊天室,供大家参考,具体内容如下服务端#!/usr/bin/env python#
- 准备工作:python:https://www.python.org/downloads/Dev-C++:https://sourcefor
- 照例使用XMLhttp同步方式获取数据,可是由于网络不稳定,经常造成'死锁'状况,既send之后一直不返回服务器结果,也不出
- 目录项目初始化选择 MQTT 客户端库Pip 安装 Paho MQTT 客户端Python MQTT 使用连接 MQTT 服务器导入 Pah
- 多模块引用由此引发的相对路径混乱当不同层级的 Python 模块相互调用时,我们会发现原本在一个模块中写死的相对路径会导致找不到文件的报错。
- 本文实例讲述了PHP实现判断二叉树是否对称的方法。分享给大家供大家参考,具体如下:问题请实现一个函数,用来判断一颗二叉树是不是对称的。注意,
- 本文实例讲述了Python运维自动化之nginx配置文件对比操作。分享给大家供大家参考,具体如下:文件差异对比diff.py#!/usr/b
- alleen 问:下面是我制作的一菜单效果,现在的问题是当我只点击一级菜单A一次的时候,一级菜单A的背景色由绿色变成了黄色,再点击一级菜单B
- 导包import “github.com/smartystreets/goconvey”核心API顶
- 需求描述有时候我们会基于已有数据生成一列在表格中,类似于下面的class BaseSchema(models.Model): ... def
- VS2013的简单WInForm控件,通过WebRequest,WebResponse来访问,接收:private void btn_int
- 什么是pyc文件pyc是一种二进制文件,是由py文件经过编译后,生成的文件,是一种byte code,py文件变成pyc文件后,加载的速度有
- 本文实例讲述了Python使用turtule画五角星的方法。分享给大家供大家参考。具体实现方法如下:#!/usr/bin/env pytho
- 1.使用jobsName.ini文件保存要创建job的名字jobs1jobs2jobs32.使用Jenkins创建job时自动生成的conf
- 本文实例讲述了Bootstrap简单实用的表单验证插件BootstrapValidator用法。分享给大家供大家参考,具体如下:Bootst
- 目录一、 环境准备:1.docker环境2.安装mariadb数据库二、ORM1.ORM简介2.django配置数据库第一种方式:第二种方式
- 我就废话不多说了,大家还是直接看代码吧!import cv2# 读取图片并缩放方便显示img = cv2.imread('D:/6.
- #!/usr/bin/env python# -*- coding: utf8 -*-import MySQLdbimport timeim
- 一、触发器1.触发器在数据库里以独立的对象存储,2.触发器不需要调用,它由一个事件来触发运行3.触发器不能接收参数--触发器的应用举个例子:
- 接口模块需要用 API 来提供对外服务的接口,当然也可以直接连数据库来取,但是这样就需要知道数据库的连接信息,不太安全,而且需要配置连接,所