1. 程式人生 > 實用技巧 >python爬蟲學習筆記(二十八)-Scrapy 框架 爬取JS生成的動態頁面

python爬蟲學習筆記(二十八)-Scrapy 框架 爬取JS生成的動態頁面

問題

有的頁面的很多部分都是用JS生成的,而對於用scrapy爬蟲來說就是一個很大的問題,因為scrapy沒有JS engine,所以爬取的都是靜態頁面,對於JS生成的動態頁面都無法獲得

官網http://splash.readthedocs.io/en/stable/

解決方案

  • 利用第三方中介軟體來提供JS渲染服務: scrapy-splash 等
  • 利用webkit或者基於webkit庫

Splash是一個Javascript渲染服務。它是一個實現了HTTP API的輕量級瀏覽器,Splash是用Python實現的,同時使用Twisted和QT。Twisted(QT)用來讓服務具有非同步處理能力,以發揮webkit的併發能力

安裝

  1. pip安裝scrapy-splash庫
 pip install scrapy-splash
  1. scrapy-splash使用的是Splash HTTP API, 所以需要一個splash instance,一般採用docker執行splash,所以需要安裝docker
  2. 安裝docker, 安裝好後執行docker
  3. 拉取映象
 docker pull scrapinghub/splash
  1. 用docker執行scrapinghub/splash
docker run -p 8050:8050 scrapinghub/splash
  1. 配置splash服務(以下操作全部在settings.py):

    1. 使用splash解析,要在配置檔案中設定splash伺服器地址:
    SPLASH_URL = 'http://192.168.99.100:8050/' 
    
    1. 將splash middleware新增到DOWNLOADER_MIDDLEWARE中
    DOWNLOADER_MIDDLEWARES = {
    'scrapy_splash.SplashCookiesMiddleware': 723,
    'scrapy_splash.SplashMiddleware': 725,
    'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
    }
    
    1. Enable SplashDeduplicateArgsMiddleware
    SPIDER_MIDDLEWARES = {
      'scrapy_splash.SplashDeduplicateArgsMiddleware': 100
    }
    

    這個中介軟體需要支援cache_args功能; 它允許通過不在磁碟請求佇列中多次儲存重複的Splash引數來節省磁碟空間。如果使用Splash 2.1+,則中介軟體也可以通過不將這些重複的引數多次傳送到Splash伺服器來節省網路流量

    1. 配置訊息佇列所使用的過濾類
    DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
    
    1. 配置訊息佇列需要使用的類
    HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
    

樣例

import scrapy
from scrapy_splash import SplashRequest


class DoubanSpider(scrapy.Spider):
    name = 'douban'

    allowed_domains = ['douban.com']


def start_requests(self):
    yield SplashRequest('https://movie.douban.com/typerank?type_name=劇情&type=11&interval_id=100:90', args={'wait': 0.5})


def parse(self, response):
    print(response.text)