Scrapy爬图片入门——静态网站

一、要爬的网站:

二、建个项目:

scrapy startproject demo
scrapy genspider image 网站域名

spiders下的image.py是scrapy自动为我们生成的

三、编辑image.py

用xpath提取我们需要的网站内容(图片标题以及链接)

import scrapy

from ..items import DemoItem


class ImageSpider(scrapy.Spider):
    name = 'image'
    allowed_domains = ['https://www.58pic.com/c/24601329']
    start_urls = ['https://www.58pic.com/c/24601329']

    def parse(self, response):
        img_list=response.xpath("//div[@class='list-box col-s-960 clearfix ']/div")
        print(img_list)
        for img in img_list:
             item=DemoItem()
             item["title"]=img.xpath("./a/div[2]/span[2]/text()").extract_first()+'.png'
             item["img_urls"]='http:'+img.xpath("./a/div[@class='image-box']/img/@data-original")[0].extract()
             yield item

 四、编辑items.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class DemoItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    img_urls = scrapy.Field()
    pass

五、编辑pipelines.py

from scrapy.pipelines.images import ImagesPipeline
import scrapy
import os


class DemoPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        yield scrapy.Request(url=item['img_urls'], meta={'item': item})

    # 返回图片名称即可
    def file_path(self, request, response=None, info=None):
        item = request.meta['item']
        print('########', item)
        filePath = item['title']
        return filePath

    def item_completed(self, results, item, info):
        return item

 六、修改setting文件

1.把管道打开:

ITEM_PIPELINES:项目管道,300为优先级,越低越爬取的优先度越高

2.其他:

BOT_NAME:项目名

LOG_LEVEL:屏蔽warning

USER_AGENT:默认是注释的,这个东西非常重要,不写容易被判断为电脑,简单点写一个Mozilla/5.0即可

ROBOTSTXT_OBEY:是否遵循机器人协议,默认是true,需要改为false,否则很多东西爬不了

 七、开始爬虫:

scrapy crawl image

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我啊困的唉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值