使用splash进行javascript预处理
软件开发 splash
2019年6月28日

介绍

Splash是一个Javascript渲染服务。它是一个实现了HTTP API的轻量级浏览器,Splash是用Python实现的,同时使用Twisted和QT。Twisted(QT)用来让服务具有异步处理能力,以发挥webkit的并发能力。

服务器部署

docker run -p 5023:5023 -p 8050:8050 -p 8051:8051 scrapinghub/splash

代码示例

# splash server 地址
splash_url = 'http://splash.server/render.html'

def splash_render(self, url, cookies=None, proxy=None, wait=5):
        """
        splash请求
        :param url:
        :param cookies: dict like {'a': '1', 'b': 'c'}
        :param proxy: string like '127.0.0.1:1080'
        :param wait: int
        :return:
        """
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) '
                          'AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/72.0.3626.119 Safari/537.36',
        }

        if cookies:
            headers['Cookie'] = cookie2str(cookies)

        args = {
            'url': url,
            'wait': wait,
            'headers': headers,
        }
        if proxy:
            args['proxy'] = 'http://{}'.format(proxy)
        return requests.post(splash_url, json=args)

最后修改于: 2023年8月9日 17:05