Python爬虫大数据 爬虫Python AI Sql程序员

爬虫课堂(二十三)|使用Splash爬取动态页面(1)

2018-03-28  本文已影响0人  小怪聊职场

在之前的章节中,爬取的都是静态页面中的信息,随着越来越多的网站开始用JS在客户端浏览器动态渲染网站,导致很多需要的数据并不能在原始的HTML中获取,再加上Scrapy本身并不提供JS渲染解析的功能,那么如何通过Scrapy爬取动态网站的数据呢?这一章节我们将学习这些知识。
通常对这类网站数据的爬取采用如下两种方法:

一、搭建Splash服务
如何在Scrapy中调用Splash服务?Python库的scrapy-splash是一个非常好的选择,下面就来讲解如何使用scrapy-splash。

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"`
$ brew install docker
Using default tag: latest
Warning: failed to get default registry endpoint from daemon (Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?). Using system default: https://index.docker.io/v1/
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

问题原因是因为docker服务没有启动,在相应的/var/run/ 路径下找不到docker的进程。
执行service docker start命令,启动docker服务。

DOWNLOADER_MIDDLEWARES = {
    'scrapy_splash.SplashCookiesMiddleware': 723,
    'scrapy_splash.SplashMiddleware': 725,
    'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}

3)支持cache_args(可选):

SPIDER_MIDDLEWARES = {
    'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}

4)设置去重过滤器:
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
二、使用Splash服务
Splash功能丰富,包含多个服务端点,最常用的有两个端点:

举一个简单的例子,使用scrapy_splash.SplashRequest渲染JS请求,如下:

import scrapy
from scrapy_splash import SplashRequest

class MySpider(scrapy.Spider):
    # 假设这个请求的页面数据是需要执行JS才能爬取的
    start_urls = ["http://example.com"]

    def start_requests(self):
        for url in self.start_urls:
            yield SplashRequest(url, self.parse, args={'images':0,'timeout': 5})

    def parse(self, response):
        # ...        

上述代码中,用户只需使用scrapy_splash.SplashRequest替代scrapy.Request提交请求即可完成JS渲染,并且在SplashRequest的构造器中无须传递endpoint参数,因为该参数默认值就是‘render.html’。
下面介绍下SplashRequest构造器方法中的一些常用参数。

上一篇 下一篇

猜你喜欢

热点阅读