Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地

Python爬虫:爬取某鱼颜值主播图片并保存到本地

    • 一、准备
    • 二、分析
    • 三、完整代码

一、准备

1.创建scrapy项目

scrapy startproject douyu

cd douyu

scrapy genspider spider "www.douyu.com"

Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地_第1张图片
2.创建启动文件start.py

from scrapy import cmdline

cmdline.execute("scrapy crawl douyu".split())

二、分析

准备完毕,开始分析。
先进入斗鱼看看。
Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地_第2张图片

找到发送的请求
Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地_第3张图片
可以看到页面的数据都在其中
Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地_第4张图片
而请求的链接为
Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地_第5张图片
访问该网址
Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地_第6张图片
这么看数据可能不太好分析,复制数据使用在线json进行格式化校验
Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地_第7张图片
本次项目中要获取的是主播名称和图片url,分析json数据如下:
Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地_第8张图片
我们需要的数据位置:
Python爬虫:基于Scrapy的爬取某鱼颜值主播图片并保存到本地_第9张图片

OK,接下来分析代码

class DouyuSpider(scrapy.Spider):
    name = 'spider'
    # allowed_domains = ['www.douyu.com']
    #直接访问我们刚才找到的链接
    start_urls = ['https://www.douyu.com/gapi/rknc/directory/yzRec/1']

    def parse(self, response):
        offset = 1
        #通过对json的分析,名称和图片都在rl下,我们直接拿到data下的rl进行遍历获取
        data_list = json.loads(response.body)["data"]["rl"]
        for data in data_list:
            nn = data["nn"]  #拿到名称
            img_url = data["rs1"]  #拿到图片url
            item = DouyuItem(nn=nn,img_url=img_url)
            yield item

		#爬取多页,只需改变最后的数字,进行回调访问
        offset += 1   
        if offset < 4:
            url = "https://www.douyu.com/gapi/rknc/directory/yzRec/" + str(offset)
            yield scrapy.Request(url=url,callback=self.parse,encoding="utf-8",dont_filter=True)
class DouyuPipeline(ImagesPipeline):

    #get_media_requests,该函数的作用是下载图片
    def get_media_requests(self, item, info):
        image_link = item["img_url"]
        yield scrapy.Request(image_link)

    # def file_path(self, request, response=None, info=None):
    #     img_name = request.meta['item']['nn']

    # def file_path(self, request, response=None, info=None):
    #     image_guid = "666"
    #     return 'full/%s.jpg' % (image_guid)

    def item_completed(self, results, item, info):
    	#看下分面分析
        image_path = [x['path'] for ok, x in results if ok]
        # print('图片路径是:', settings.IMAGES_STORE + '/' + image_path[0])
        os.rename(settings.IMAGES_STORE + '/' + image_path[0], settings.IMAGES_STORE + '/' + item["nn"] + '.jpg')
        return item

通过打印results,可知其是如下格式:
有一个参数为元组,元组有两个参数
在这里插入图片描述
打印results[0]得:
在这里插入图片描述
打印results[0]1][‘path’]得到path:
在这里插入图片描述

image_path = [x['path'] for ok, x in results if ok]

使用推导式写法

x in results if ok  迭代results条件为True也就是ok
为True也就是ok得话
x['path'] for ok   把path、取出来
os.rename(settings.IMAGES_STORE + '/' + image_path[0], settings.IMAGES_STORE + '/' + item["nn"] + '.jpg')

对图片进行重命名or.rename("之前的名称","新名称")

三、完整代码

spider.py

# -*- coding: utf-8 -*-
import scrapy
import json
from douyu.items import DouyuItem


class DouyuSpider(scrapy.Spider):
    name = 'spider'
    # allowed_domains = ['www.douyu.com']
    start_urls = ['https://www.douyu.com/gapi/rknc/directory/yzRec/1']

    def parse(self, response):
        offset = 1
        data_list = json.loads(response.body)["data"]["rl"]
        for data in data_list:
            nn = data["nn"]
            img_url = data["rs1"]
            item = DouyuItem(nn=nn,img_url=img_url)
            yield item

        offset += 1
        if offset < 4:
            url = "https://www.douyu.com/gapi/rknc/directory/yzRec/" + str(offset)
            yield scrapy.Request(url=url,callback=self.parse,encoding="utf-8",dont_filter=True)

pipelines.py

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

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

class DouyuPipeline(ImagesPipeline):

    #get_media_requests,该函数的作用是下载图片
    def get_media_requests(self, item, info):
        image_link = item["img_url"]
        yield scrapy.Request(image_link)


    def item_completed(self, results, item, info):
        image_path = [x['path'] for ok, x in results if ok]
        # print('图片路径是:', settings.IMAGES_STORE + '/' + image_path[0])
        os.rename(settings.IMAGES_STORE + '/' + image_path[0], settings.IMAGES_STORE + '/' + item["nn"] + '.jpg')
        return item

items.py

# -*- coding: utf-8 -*-

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

import scrapy


class DouyuItem(scrapy.Item):

    nn = scrapy.Field()  #主播名称
    img_url = scrapy.Field() #直播间封面

settings.py

# -*- coding: utf-8 -*-

# Scrapy settings for douyu project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'douyu'

SPIDER_MODULES = ['douyu.spiders']
NEWSPIDER_MODULE = 'douyu.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'douyu (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

LOG_LEVEL = "ERROR"

# 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://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# 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',
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'douyu.middlewares.DouyuSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'douyu.middlewares.DouyuDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'douyu.pipelines.DouyuPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.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://docs.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'

import os

IMAGES_STORE = "download"

本次项目到此结束,觉得不错的小伙伴可以点赞收藏哦,谢谢各位!

你可能感兴趣的:(Python爬虫,python,爬虫,后端,json,pycharm)