# 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# useful for handling different item types with a single interfacefrom scrapy.pipelines.images import ImagesPipeline
from scrapy import Request
import pymongoclassLianjiaPipeline(object):# 設置存儲文檔名稱collection_name ='secondhandhouse'def__init__(self, mongo_uri, mongo_db):self.mongo_uri = mongo_uriself.mongo_db = mongo_db@classmethoddeffrom_crawler(cls, crawler):return cls(# 通過crawler獲取settings文件,獲取其中的MongoDB配置信息mongo_uri=crawler.settings.get('MONGO_URI'),mongo_db=crawler.settings.get('MONGO_DATABASE','lianjia'))defopen_spider(self,spider):# 當爬蟲打開時連接MonoDB數據庫# 先連接Server,再連接指定數據庫self.client = pymongo.MongoClient(self.mongo_uri)self.db = self.client[self.mongo_db]defclose_spider(self,spider):# 爬蟲結束時關閉數據庫連接self.client.close()defprocess_item(self, item, spider):# 將item插入數據庫self.db[self.collection_name].insert(dict(item))return itemclassLianjiaImagePipeline(ImagesPipeline):defget_media_requests(self, item, info):for image_url in item['images_urls']:# 將圖片地址傳入Request,進行下載,同時將item參數添加到Request中yield Request(image_url, meta={'item':item})deffile_path(self, request, response=None, info=None,*, item=None):# 從Request中獲取item,以房屋標題作為文件夾名稱item = request.meta['item']image_folder = item['house_name']# 使用圖片URL作為圖片存儲名稱image_guild = request.url.split('/')[-1]# 圖片保存,文件夾/圖片image_save = u'{0}/{1}'.format(image_folder,image_guild)return image_save
在settings.py中激活Pipeline,設置圖片存儲信息、MongoDB數據信息。
# Scrapy settings for lianjia 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.htmlBOT_NAME ='lianjia'SPIDER_MODULES =['lianjia.spiders']
NEWSPIDER_MODULE ='lianjia.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent#USER_AGENT = 'lianjia (+http://www.yourdomain.com)'# Obey robots.txt rules
ROBOTSTXT_OBEY =False# 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',#}# Enable or disable spider middlewares# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES ={'lianjia.middlewares.LianjiaSpiderMiddleware':543,}# Enable or disable downloader middlewares# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES ={'lianjia.middlewares.LianjiaDownloaderMiddleware':543,}# 代理IP需要自己去找,我是在[芝麻代理](http://www.zhimaruanjian.com/?utm-source=bdtg&utm-keyword=?246)這個網站找的,每天可以免費領取20個IP,這不是打廣告
PROXY_LIST=['http://182.240.0.146:4245','http://114.96.196.244:4264','http://58.218.201.114:7007','http://59.58.43.88:4235','http://218.95.115.97:4254','http://220.164.105.19:4228','http://125.111.151.110:4205','http://106.125.163.111:4257']# 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 ={'lianjia.pipelines.LianjiaPipeline':300,'lianjia.pipelines.LianjiaImagePipeline':400}
IMAGES_STORE ='D:\\pycharm\\pych\\scrapy\\lianjia\\images'
IMAGES_URLS_FIELD ='images_urls'
IMAGES_RESULT_FIELD ='images'# MongoDB配置信息
MONGO_URI ='localhost:27017'
MONGO_DATABASE ='lianjia'# 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'
在middleware.py寫Spider中間件和Downloader中間件
# Define here the models for your spider middleware## See documentation in:# https://docs.scrapy.org/en/latest/topics/spider-middleware.htmlfrom scrapy import signals
import scrapy
import random# useful for handling different item types with a single interfacefrom itemadapter import is_item, ItemAdapterclassLianjiaSpiderMiddleware(object):# Not all methods need to be defined. If a method is not defined,# scrapy acts as if the spider middleware does not modify the# passed objects.# 利用Scrapy數據收集功能記錄相同小區的數量def__init__(self, stats):self.stats = stats@classmethoddeffrom_crawler(cls, crawler):# This method is used by Scrapy to create your spiders.return cls(stats=crawler.stats)defprocess_spider_input(self, response, spider):# Called for each response that goes through the spider# middleware and into the spider.# Should return None or raise an exception.returnNonedefprocess_spider_output(self, response, result, spider):# Called with the results returned from the Spider, after# it has processed the response.# Must return an iterable of Request, or item objects.# 從item中獲取小區名稱,在數據收集中幾率相同小區的數量for item in result:ifisinstance(item,scrapy.Item):# 從result中的item獲取小區名稱community_name = item['community_name']# 在數據統計中為相同的小區增加數值self.stats.inc_value(community_name)yield itemdefprocess_spider_exception(self, response, exception, spider):# Called when a spider or process_spider_input() method# (from other spider middleware) raises an exception.# Should return either None or an iterable of Request or item objects.passdefprocess_start_requests(self, start_requests, spider):# Called with the start requests of the spider, and works# similarly to the process_spider_output() method, except# that it doesn’t have a response associated.# Must return only requests (not items).for r in start_requests:yield rdefspider_opened(self, spider):spider.logger.info('Spider opened: %s'% spider.name)classLianjiaDownloaderMiddleware(object):# 為請求添加代理def__init__(self, proxy_list):self.proxy_list = proxy_list@classmethoddeffrom_crawler(cls, crawler):# This method is used by Scrapy to create your spiders.# 從settings.py中獲取代理列表return cls(proxy_list=crawler.settings.get('PROXY_LIST'))defprocess_request(self, request, spider):# 從代理列表中隨機選取一個添加至請求proxy = random.choice(self.proxy_list)request.meta['proxy']= proxydefprocess_response(self, request, response, spider):# Called with the response returned from the downloader.# Must either;# - return a Response object# - return a Request object# - or raise IgnoreRequestreturn responsedefprocess_exception(self, request, exception, spider):# Called when a download handler or a process_request()# (from other downloader middleware) raises an exception.# Must either:# - return None: continue processing this exception# - return a Response object: stops process_exception() chain# - return a Request object: stops process_exception() chainpassdefspider_opened(self, spider):spider.logger.info('Spider opened: %s'% spider.name)