吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 6232|回复: 15
收起左侧

[Python 转载] Scrapy框架爬取妹子图保存到不同目录下

[复制链接]
锋逸520 发表于 2018-7-29 18:49
进行设置settings
[Asm] 纯文本查看 复制代码
#启动图片管道
ITEM_PIPELINES = {
   'mztu.pipelines.ImagesPipelinse': 300,
}
#设置默认目录地址  注意下载图片的话默认地址必须设置!!!
IMAGES_STORE = "E:\study\Python\scrapy\mztu\imges"
#设置图片通道失效时间
IMAGES_EXPIRES =90
#缩略图生成
#IMAGES_THUMBS = {
 #   'small': (50, 50),
#    'big': (270, 270),
#}


spider目录

[Python] 纯文本查看 复制代码
# -*- coding: utf-8 -*-
import scrapy
from mztu.items import MztuItem

class ZimdgSpider(scrapy.Spider):
    name = 'zimdg'
    allowed_domains = ['mzitu.com']
    #生成链接列表
    start_urls = ['http://www.mzitu.com/xinggan/page/{}/'.format(str(x)) for x in range(118)]
    def parse(self, response):
        #解析出链接
        set_li = response.xpath("//div[@class='postlist']/ul/li")
        for ecth in set_li:
            ed = ecth.xpath('./a/@href').extract()
            #进行二次分类解析
            yield scrapy.Request(ed[0],callback=self.parse_item)


    def parse_item(self,response):
        itme = MztuItem()
        # 获取页数链接进行访问
        offset = int(response.xpath('//div[@class="pagenavi"]/a/span/text()')[4].extract())
        #生成链接访问
        #遍历链接访问
        for i in [response.url+"/{}".format(str(x))  for x in range(1,offset+1)]:
            itme['Referer']=i
            #将meta传入链接
            yield scrapy.Request(itme['Referer'],meta={'meta_1':itme}, callback=self.parse_ponse)
        # for i in url:

    def parse_ponse(self,response):
        #获取itme资源
        itme = response.meta['meta_1']
        #获取图片地址
        imgs = response.xpath('//div[@class="main-image"]/p/a/img/@src')[0].extract()
        #获取图片目录
        title = response.xpath('//div[@class="main-image"]/p/a/img/@alt')[0].extract()
        itme["title"]= title
        itme["imge_url"]= imgs
        #itme["nickname"] = itme["Referer"][itme["Referer"].rfind("/"):]+itme["imge_url"][itme["imge_url"].rfind('/')+1:itme["imge_url"].rfind('.')]
        #itme["nickname"] = itme["imge_url"][itme["imge_url"].rfind('/')+1:itme["imge_url"].rfind('.')]
        yield itme


items
[Python] 纯文本查看 复制代码
import scrapy


class MztuItem(scrapy.Item):
    #目录
    title = scrapy.Field()
    #图片地址
    imge_url = scrapy.Field()
    #请求头
    Referer = scrapy.Field()

    image_Path = scrapy.Field()
    #图片名称
   # nickname = scrapy.Field()

pipelines管道
[Python] 纯文本查看 复制代码
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
# 导入这个包为了移动文件
import shutil
#此包不解释
import scrapy
# 导入项目设置
from scrapy.utils.project import get_project_settings
# 导入scrapy框架的图片下载类
from scrapy.pipelines.images import ImagesPipeline
#此包不解释
import os

class ImagesPipelinse(ImagesPipeline):
    #def process_item(self, item, spider):
    #    return item
    # 获取settings文件里设置的变量值
    IMAGES_STORE = get_project_settings().get("IMAGES_STORE")
    # 重写ImagesPipeline类的此方法
    # 发送图片下载请求
    def get_media_requests(self, item, info):
        image_url = item["imge_url"]
        #headers是请求头主要是防反爬虫
        yield scrapy.Request(image_url,headers={'Referer':item['Referer']})

    def item_completed(self, result, item, info):
        image_path = [x["path"] for ok, x in result if ok]
        # 定义分类保存的路径
        img_path = "%s\%s" % (self.IMAGES_STORE, item['title'])
        # 目录不存在则创建目录
        if os.path.exists(img_path) == False:
            os.mkdir(img_path)
        # 将文件从默认下路路径移动到指定路径下
        shutil.move(self.IMAGES_STORE + "\\" +image_path[0], img_path + "\\" +image_path[0][image_path[0].find("full\\")+6:])
        item['image_Path'] = img_path + "\\" + image_path[0][image_path[0].find("full\\")+6:]
        return item

这里实现图片保存到不同的目录下,主要函数是shutil.move(),将图片从原始默认路径移动到指定目录下

免费评分

参与人数 3吾爱币 +2 热心值 +3 收起 理由
宙宇洪荒 + 1 + 1 热心回复!
one486 + 1 看到妹子我就进来了......
Artifice + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

Quincy379 发表于 2018-7-30 06:57
把完整代码放一下啊亲!
 楼主| 锋逸520 发表于 2018-7-30 08:37
Quincy379 发表于 2018-7-30 06:57
把完整代码放一下啊亲!

完整代码链接:https://pan.baidu.com/s/13UKRMqOEhqfNYmnRH126Hw 密码:8da7

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
Quincy379 + 1 + 1 谢谢@Thanks!

查看全部评分

oy520920 发表于 2018-7-29 20:29
45454644756

免费评分

参与人数 1吾爱币 -3 收起 理由
苏紫方璇 -3 请勿灌水,提高回帖质量是每位会员应尽的义务!

查看全部评分

www1678 发表于 2018-7-29 19:06
看到妹子图我就进来了
abc002 发表于 2018-7-29 19:07
感谢分享
AngelEyes145 发表于 2018-7-29 19:48
学习了!!!!!!!!!
夏橙M兮 发表于 2018-7-29 21:05
感谢分享。
lunaaero 发表于 2018-7-29 21:10
学习了!!!
笨笨猪 发表于 2018-7-29 21:28
楼主重写了imagepipeline两个函数,get_media_requests和itemn_competed,还是挺主流的管道下载图片的方式
Artifice 发表于 2018-7-29 21:30
感谢分享
头像被屏蔽
one486 发表于 2018-7-29 21:40
提示: 作者被禁止或删除 内容自动屏蔽
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-30 19:49

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表