Scrapy框架之Scrapy-Splash的使用 https://github.com/scrapy-plugins/scrapy-splash
1.安装python3.7
2.安装pip3
3.安装 python3组件
pip3 install scrapy
pip3 install requests
pip3 install scrapy-splash
pip3 install pymysql
docker 安装
首先需要启动Splash,启动命令如下
docker run -p 8050:8050 scrapinghub/splash
然后在对应scrapy项目的settings里面配置Splash服务的地址,例如:
SPLASH_URL = 'http://192.168.59.103:8050'
#. 在settings中的DOWNLOADER_MIDDLEWARES 加上splash的中间件,并设置 HttpCompressionMiddleware 对象的优先级
DOWNLOADER_MIDDLEWARES = { 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, }
#. 在SPIDER_MIDDLEWARES 中安装splash的 SplashDeduplicateArgsMiddleware 中间件
SPIDER_MIDDLEWARES = { 'scrapy_splash.SplashDeduplicateArgsMiddleware': 100, }
#. 您还可以设置对应的过滤中间件——DUPEFILTER_CLASS
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
#. 您可以设置scrapy.contrib.httpcache.FilesystemCacheStorage 来使用Splash的HTTP缓存
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage' 用法
如果要使用Splash来对页面进行渲染,您可以使用SplashRequest来代替原始scrapy中的Request, 示例如下:
yield SplashRequest(url, self.parse_result, callback #任务完成之后对应的回调函数 #args设置的是端点API的参数,关于API参数问题,请参考: `Splash HTTP API <./api.html>`_ args={ # 可选参数,表示spalsh在执行完成之后会等待一段时间后返回 'wait': 0.5, #url是一个必须的参数,表明将要对哪个url进行请求 'url' : "http://www.example.com", #http_method:表示Splash将向目标url发送何种请求 'http_method': 'GET' # 'body' 用于POST请求,作为请求的请求体 # 'lua_source' 如果需要执行lua脚本,那么这个参数表示对应lua脚本的字符串 }, endpoint='render.json', # optional; default is render.html splash_url='<url>', # optional; overrides SPLASH_URL slot_policy=scrapy_splash.SlotPolicy.PER_DOMAIN, # optional, # "meta" 是一个用来向回调函数传入参数的方式,在回调函数中的response.meta中可以取到这个地方传入的参数 )
具体文档:https://splash.readthedocs.io/en/stable/scripting-overview.html