Scrapy——5 下載中間件經常使用函數、scrapy怎麼對接selenium、經常使用的Setting內置設置有哪些

Scrapy——5html

 

  1. 下載中間件經常使用的函數
  2. Scrapy怎樣對接selenium
  3. 經常使用的setting內置設置
  4. 對接selenium實戰

 

(Downloader Middleware)下載中間件經常使用函數有哪些web

 Scrapy怎樣對接Selenium服務器

設置setting.py裏的DOWNLOADER_MIDDLIEWARES,添加本身編寫的下載中間件類cookie

 

 經常使用的Setting內置設置有哪些併發

詳情能夠參考https://scrapy-chs.readthedocs.io/zh_CN/1.0/topics/settings.html#concurrent-itemsdom

  • CONCURRENT_REQUESTS

  • 默認: 16
  • Scrapy downloader 併發請求(concurrent requests)的最大值。
  • CONCURRENT_ITEMS

  • 默認: 100
  • Item Processor(即 Item Pipeline) 同時處理(每一個response的)item的最大值。
  • DOWNLOAD_TIMEOUT

  • 默認: 180
  • 下載器超時時間(單位: 秒)。
  • DOWNLOAD_DELAY

  • 默認: 0
  • 下載器在下載同一個網站下一個頁面前須要等待的時間。該選項能夠用來限制爬取速度, 減輕服務器壓力。同時也支持小數:
    DOWNLOAD_DELAY = 0.25    # 250 ms of delay
  • 該設定影響(默認啓用的) RANDOMIZE_DOWNLOAD_DELAY 設定。 默認狀況下,Scrapy在兩個請求間不等待一個固定的值, 而是使用0.5到1.5之間的一個隨機值 * DOWNLOAD_DELAY 的結果做爲等待間隔。
  • 當 CONCURRENT_REQUESTS_PER_IP 非0時,延遲針對的是每一個ip而不是網站。
  • 另外您能夠經過spider的 download_delay 屬性爲每一個spider設置該設定。
  • LOG_ENCODING

  • 默認: 'utf-8'
  • logging使用的編碼。
  • ITEM_PIPELINES

  • 默認: {}
  • 保存項目中啓用的pipeline及其順序的字典。該字典默認爲空,值(value)任意。 不過值(value)習慣設定在0-1000範圍內。
  • COOKIES_ENABLED

  • 默認: True
  • 是否啓用cookies middleware。若是關閉,cookies將不會發送給web server。

 

對接selenium實戰——PM2.5歷史數據_空氣質量指數歷史數據_中國空氣質量在線監測分析平...scrapy

此網站的數據都是經過加密傳輸的,咱們能夠經過對接selenium跳過數據加密過程,直接獲取到網頁js渲染後的代碼,達到數據的提取ide

惟一的缺點就是速度太慢函數

  • 首先建立項目(光標所在的文件是日誌文件)

本次實戰旨在selenium的對接,就不考慮保存數據的問題,因此不用配置items文件網站

  • /area/area/settings.py    設置無視爬蟲協議,設置對應下載中間件的激活,日誌等級(設置日誌等級後運行程序會生成相應的日誌信息,主要的做用是爲了屏蔽程序運行時過多的日誌,方便觀察運行結果)
  • /area/area/spiders/aqistudy.py    直接編寫代碼
    # -*- coding: utf-8 -*-
    import scrapy
    
    
    class AqistudySpider(scrapy.Spider):
        name = 'aqistudy'
        # allowed_domains = ['aqistudy.cn']
        start_urls = ['https://www.aqistudy.cn/historydata/']
    
        def parse(self, response):
            print('開始獲取主要城市地址...')
            city_list = response.xpath("//ul[@class='unstyled']/li/a/@href").extract()
    
            for city_url in city_list[1:3]:
                yield scrapy.Request(url=self.start_urls[0]+city_url, callback=self.parse_month)
    
        def parse_month(self, response):
            print('開始獲取當前城市的月份地址...')
            month_urls=  response.xpath('//ul[@class="unstyled1"]/li/a/@href').extract()
    
            for month_url in month_urls:
                yield scrapy.Request(url=self.start_urls[0]+month_url, callback=self.parse_day)
    
        def parse_day(self, response):
            print('開始獲取空氣數據...')
            print(response.xpath('//h2[@id="title"]/text()').extract_first()+'\n')
            item_list = response.xpath('//tr')[1:]
            for item in item_list:
                print('day: '+item.xpath('./td[1]/text()').extract_first() + '\t' 
                      + 'API: '+item.xpath('./td[2]/text()').extract_first() + '\t' 
                      + '質量: '+item.xpath('./td[3]/span/text()').extract_first() + '\t' 
                      + 'MP2.5: '+item.xpath('./td[4]/text()').extract_first() + '\t' 
                      + 'MP10: '+item.xpath('./td[5]/text()').extract_first() + '\t' 
                      + 'SO2: '+item.xpath('./td[6]/text()').extract_first() + '\t' 
                      + 'CO: '+item.xpath('./td[7]/text()').extract_first() + '\t' 
                      + 'NO2: '+item.xpath('./td[8]/text()').extract_first() + '\t' 
                      + 'O3_8h: '+item.xpath('./td[9]/text()').extract_first()
                      )
  • /area/area/middlewares.py    設置下載中間件
  • 程序代碼發起requests的時候,都會通過中間件,因此用了一個 if 'month' in request.url:來區分
  • 此處對接的是PhantomJS,也能夠用別的驅動程序,用Chrome的話,必定也要記得設置無窗口模式,不然會不一樣的彈出窗口,更多關於selenium啓動項的知識,能夠參考此處
  • middlewares.py用到的類是自定義的,因此在前面的設置中,激活的是相應的中間件
    # -*- coding: utf-8 -*-
    
    # Define here the models for your spider middleware
    #
    # See documentation in:
    # https://doc.scrapy.org/en/latest/topics/spider-middleware.html
    
    import time
    from selenium import webdriver
    import scrapy
    from scrapy import signals
    
    class AreaSpiderMiddleware(object):
        ......
    
    class AreaDownloaderMiddleware(object):
        ......
    
    class AreaMiddleware(object):
    
        def process_request(self, request, spider):
            self.driver = webdriver.PhantomJS()
    
            if 'month' in request.url:
                self.driver.get(request.url)
                time.sleep(2)
                html = self.driver.page_source
                self.driver.quit()
    
                return scrapy.http.HtmlResponse(url=request.url, body=html,request=request, encoding='utf-8' )
  •  由於筆者的虛擬機是服務器模式(命令行窗口,沒法運行selenium),因此程序是在Windows中運行的。在項目文件中的main.py文件,就是一個運行程序的文件
  • 這幾行就能夠將scrapy的多個程序綜合在一個程序中運行了,前提是你爲你的Windows安裝了selenium的相應驅動Scrapy庫
    # -*- coding: utf-8 -*-
    # @Time    : 2018/11/12 16:56
    # @Author  : wjh
    # @File    : main.py
    from scrapy.cmdline import execute
    execute(['scrapy','crawl','aqistudy'])

 運行結果以下:

相關文章
相關標籤/搜索