使用Scrapy爬取斗鱼图片
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                使用Scrapy爬取斗鱼图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                1.具體文件結構
 
 
2.代碼:
 
items
 
# -*- coding: utf-8 -*-# Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass DouyuItem(scrapy.Item):# define the fields for your item here like:nickname = scrapy.Field()imagelink = scrapy.Field()imagePath = scrapy.Field()#pass
douyumeinv
# -*- coding: utf-8 -*- import scrapy from douyu.items import DouyuItem import jsonclass DouyumeinvSpider(scrapy.Spider):#爬蟲名name = "douyumeinv"#表示允許爬蟲爬的網站allowed_domains = ["capi.douyucdn.cn"]#拼接請求鏈接offset = 0url = "http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=20&offset="start_urls = [url + str(offset)]def parse(self, response):# 把json格式的數據轉換為python格式,data段是列表data = json.loads(response.text)["data"]#遍歷數據獲取值for each in data:item = DouyuItem()item["nickname"] = each["nickname"]item["imagelink"] = each["vertical_src"]yield item#獲取下一頁的數據self.offset += 20yield scrapy.Request(self.url + str(self.offset), 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.htmlimport scrapy import os from scrapy.utils.project import get_project_settings from scrapy.pipelines.images import ImagesPipelineclass DouyuPipeline(ImagesPipeline):# def process_item(self, item, spider):# return item#設置圖片保存路徑IMAGES_STORE = get_project_settings().get("IMAGES_STORE")def get_media_requests(self, item, info):#獲取圖片鏈接image_url = item["imagelink"]#發送圖片鏈接請求yield scrapy.Request(image_url)def item_completed(self, result, item, info):image_path = [x["path"] for ok, x in result if ok]#更改文件名os.rename(self.IMAGES_STORE + "/" + image_path[0], self.IMAGES_STORE + "/" + item["nickname"] + ".jpg")#更愛圖片路徑名item["imagePath"] = self.IMAGES_STORE + "/" + item["nickname"]return item
settings
 
# -*- 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: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.htmlBOT_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 = True# Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32# Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.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 = {"User-Agent" : "DYZB/1 CFNetwork/808.2.16 Darwin/16.3.0"# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',# 'Accept-Language': 'en', }# Enable or disable spider middlewares # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'douyu.middlewares.DouyuSpiderMiddleware': 543, #}# Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'douyu.middlewares.MyCustomDownloaderMiddleware': 543, #}# Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #}# Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = {'douyu.pipelines.DouyuPipeline': 300, } IMAGES_STORE = "Images" # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.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 http://scrapy.readthedocs.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'
啟動:
cd 到項目目錄
scrapy crawl 爬蟲名
 
結果:
 
總結
以上是生活随笔為你收集整理的使用Scrapy爬取斗鱼图片的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        