需要学习的知识:

1.获取到的json数据如何处理

2.保存到json文件

3.保存到MongoDB数据库

4.下载项目图片(含缩略图)

1.创建项目

scrapy startproject gank

2.生成项目爬虫文件

scrapy genspider gank_img gank.io

注意:项目名称gank不能跟项目爬虫文件名gank_img一致

3.gank_img.py文件

import json
import scrapy
from gank.items import GankItem class GankImgSpider(scrapy.Spider):
name = 'gank_img'
allowed_domains = ['gank.io']
# 开始链接为什么要这样写请参考:https://www.cnblogs.com/sanduzxcvbnm/p/10271493.html
start_urls = ['https://gank.io/api/data/福利/700/1'] def parse(self, response):
# 返回的是json字符串,转换成字典,提取出需要的字段
results = json.loads(response.text)['results'] for i in results:
item = GankItem()
item['who'] = i['who']
item['url'] = i['url'] yield item

4.items.py文件

import scrapy

class GankItem(scrapy.Item):
# define the fields for your item here like:
who = scrapy.Field()
url = scrapy.Field()
# 保存图片,生成图片路径
image_paths = scrapy.Field()

5.pipelines.py文件

import json
from scrapy.pipelines.images import ImagesPipeline
from scrapy.exceptions import DropItem
import pymongo
import scrapy # 在settings.py文件中开启该pipeline,则主程序中yield的数据会传输到这边来进行处理 # 保存成json文件
class JsonWriterPipeline(object): def open_spider(self, spider):
self.file = open('items.json', 'w') def close_spider(self, spider):
self.file.close() def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item # 保存到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[self.collection_name].insert_one(dict(item))
return item # 下载项目图片
class MyImagesPipeline(ImagesPipeline):
def get_media_requests(self, item, info):
# 图片链接是https的转换成http
if item['url'][0:5] == 'https':
item['url'] = item['url'].replace(item['url'][0:5], 'http')
# for image_url in item['url']:
# print('400',image_url)
yield scrapy.Request(item['url']) 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

6.settings.py文件

只修改如下配置,其余保持不变

DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,en-US;q=0.8,zh;q=0.5,en;q=0.3',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0'
} # MongoDB数据库参数
MONGO_URI = '127.0.0.1'
MONGO_DATABASE = 'gank' ITEM_PIPELINES = {
'gank.pipelines.JsonWriterPipeline': 300,
'gank.pipelines.MyImagesPipeline': 1,
'gank.pipelines.MongoPipeline': 400,
}
# 图片保存路径
IMAGES_STORE = 'D:\\gank\\images' # 90天的图片失效期限
IMAGES_EXPIRES = 90 # 缩略图
IMAGES_THUMBS = {
'small': (50, 50),
'big': (270, 270),
}

7.执行爬虫程序

scrapy crawl gank_img

8.效果

json文件

MongoDB数据库

保存的图片及缩略图

其中full为图片本身大小所存放目录,thubmbs为缩略图存放目录,缩略图有big和small两种尺寸

scrapy结尾会有相应的统计信息

下载图片561个,无法下载的图片有108个

为什么有的图片无法下载,请参考之前的文章:https://www.cnblogs.com/sanduzxcvbnm/p/10271493.html

Scrapy实战:使用scrapy再再次爬取干货集中营的妹子图片的更多相关文章

  1. Python 爬取煎蛋网妹子图片

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-08-24 10:17:28 # @Author : EnderZhou (z ...

  2. Scrapy实战篇(四)爬取京东商城文胸信息

    创建scrapy项目 scrapy startproject jingdong 填充 item.py文件 在这里定义想要存储的字段信息 import scrapy class JingdongItem ...

  3. Scrapy实战篇(五)爬取京东商城文胸信息

    创建scrapy项目 scrapy startproject jingdong 填充 item.py文件 在这里定义想要存储的字段信息 import scrapy class JingdongItem ...

  4. python爬虫–爬取煎蛋网妹子图片

    前几天刚学了python网络编程,书里没什么实践项目,只好到网上找点东西做. 一直对爬虫很好奇,所以不妨从爬虫先入手吧. Python版本:3.6 这是我看的教程:Python - Jack -Cui ...

  5. python爬虫爬取煎蛋网妹子图片

    import urllib.request import os def url_open(url): req = urllib.request.Request(url) req.add_header( ...

  6. Python爬取贴吧中的图片

    #看到贴吧大佬在发图,准备盗一下 #只是爬取一个帖子中的图片 1.先新建一个scrapy项目 scrapy startproject TuBaEx 2.新建一个爬虫 scrapy genspider ...

  7. python连续爬取多个网页的图片分别保存到不同的文件夹

      python连续爬取多个网页的图片分别保存到不同的文件夹 作者:vpoet mail:vpoet_sir@163.com #coding:utf-8 import urllib import ur ...

  8. 初识python 之 爬虫:爬取某网站的壁纸图片

    用到的主要知识点:requests.get 获取网页HTMLetree.HTML 使用lxml解析器解析网页xpath 使用xpath获取网页标签信息.图片地址request.urlretrieve ...

  9. scrapy过滤重复数据和增量爬取

    原文链接 前言 这篇笔记基于上上篇笔记的---<scrapy电影天堂实战(二)创建爬虫项目>,而这篇又涉及redis,所以又先熟悉了下redis,记录了下<redis基础笔记> ...

随机推荐

  1. 专注UI——是alert()打败了你!

    在上家公司.常常在页面上写aler()提示代码.没有认为有什么,好寻常.认为提示就本来应该是这种,可是,当我到了这家公司.在測试的时候,由于測试人员看到了一个aler弹出框.结果我的页面被退回重写,后 ...

  2. 修改this指向(bind、call 和 apply)

    一.bind 首先: var alertWrite = document.write; alertWrite('who am I?'); 这两行代码的运行结果是什么呢?不要急着回答,看完下面的内容再回 ...

  3. JpGraph中文乱码问题解决

    JpGraph是一个PHP的图形类库,可以方便地生成各种柱状图,饼图,折线图等等,而且还可以方便地加文字.但是,中文的情况就稍微麻烦了一点.在JpGraph中默认是要把字符串转成utf8的,但是如果你 ...

  4. 关于linux的用户

    1 linux支持多个用户 2 每个登陆用户有自己的shell,自己的home目录 3 可以将用户分组 4 用户对文件有各自的权限,从而将用户分割 5 用户对应属于它的一批进程 6 可以执行addus ...

  5. html5音频视频专题

    html5音频视频专题 总结 1. 操作的就是video和audio两个对象,这两个对象有他们的属性和方法,通过对象的id就可以操作他们 <audio src="../video/琴箫 ...

  6. 在IIS上搭建WebSocket服务器(三)

    编写客户端代码 1.新建一个*.html文件. ws = new WebSocket('ws://192.168.85.128:8086/Handler1.ashx?user=' + $(" ...

  7. [BZOJ 3126] Photo

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=3126 [算法] 差分约束系统 注意SPFA判负环的条件应为 : 若所有点入队次数之和 ...

  8. ngRoute (angular-route.js) 和 ui-router (angular-ui-router.js) 模块有什么不同呢?

    ngRoute (angular-route.js) 和 ui-router (angular-ui-router.js) 模块有什么不同呢? 很多文章中都有说道:当时ngRoute在路由配置时用$r ...

  9. 解决 EF where<T>(func) 查询的一个性能问题

    前两年帮朋友 做了个网吧管理软件,采用动软的三层架构 sql语句生成的.最近因功能变更 要改动,而我这段正在做asp.net mvc +ef+autofac的一个电商网站.索性 就把原来的底层全重新了 ...

  10. Android开发之Thread类分析 (转载)

    转自:http://blog.csdn.net/llping2011/article/details/9706599 在我们Linux系统中创建线程函数为:pthread_create(),在Andr ...