使用scrapy简单爬取图片并保存

第一次写博客 有什么需要改进的地方欢迎留言改进

本次代码运行是基于Linux系统 python3  scrapy框架运行

1.先看结果

2.接着上代码

spider

# -*- coding: utf-8 -*-
import scrapy


class Tu699Spider(scrapy.Spider):
    name = 'tu_699'
    allowed_domains = ['699pic.com']
    start_urls = ['http://699pic.com/people.html']

    def parse(self, response):
        li_list = response.xpath("//div[@class='swipeboxEx']/div")
        item = {}
        for li in li_list:
            # 获取图片url
            item["img_url"] = li.xpath("./a/img/@data-original").extract_first()
            # 获取图片名称
            item["img_name"] = li.xpath("./a/img/@title").extract_first()
            yield item
        # 获取下一页
        url = response.xpath("//a[@class='downPage']/@href").extract_first()
        # 判断是否为空
        if url is not None:
            # 下一页拼接
            next_url = "http://699pic.com/" + url
            # 发送下一页请求
            yield scrapy.Request(next_url, callback=self.parse)

pipelines

# -*- 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
import re
import requests

class XiaohuarPipeline(object):
    def process_item(self, item, spider):
	# 对图片的名称进行简单的处理
        item["img_name"] = re.sub(r"图片下载", "", item["img_name"])
	# 发送图片链接请求
        item["img"] = requests.get(item["img_url"])
	# 保存
        name = "tu_699/" + item["img_name"] + ".jpg"
        with open(name, 'wb') as f:
            f.write(item["img"].content)
        return item

settings
网站没有什么反扒措施
把ROBOTSTXT_OBEY该为False就好了

3.最后说明

刚学爬虫没多久 第一次尝试爬取图片 网上看其他人写的感觉有点复杂 直接自己安装思路写了个 路子有点野  还好完成了 有什么问题欢迎留言指出 共同进步(第一次写博客 比较渣 偷笑





评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值