【问题标题】:Scrapy Splash Screenshots?Scrapy Splash 截图?
【发布时间】:2017-12-23 15:28:54
【问题描述】:

我正在尝试抓取网站,同时对每个页面进行截图。到目前为止,我已经设法拼凑出以下代码:

import json
import base64
import scrapy
from scrapy_splash import SplashRequest


class ExtractSpider(scrapy.Spider):
    name = 'extract'

    def start_requests(self):
        url = 'https://stackoverflow.com/'
        splash_args = {
            'html': 1,
            'png': 1
        }
        yield SplashRequest(url, self.parse_result, endpoint='render.json', args=splash_args)

    def parse_result(self, response):
        png_bytes = base64.b64decode(response.data['png'])

        imgdata = base64.b64decode(png_bytes)
        filename = 'some_image.png'
        with open(filename, 'wb') as f:
            f.write(imgdata)

它可以很好地进入网站(例如 stackoverflow)并返回 png_bytes 的数据,但是当写入文件时 - 返回一个损坏的图像(不加载)。

有没有办法解决这个问题,或者找到更有效的解决方案?我读过 Splash Lua Scripts 可以做到这一点,但一直无法找到实现这一点的方法。谢谢。

【问题讨论】:

    标签: python lua scrapy splash-screen


    【解决方案1】:

    您正在从 base64 解码两次:

           png_bytes = base64.b64decode(response.data['png'])
           imgdata = base64.b64decode(png_bytes)
    

    简单地做:

        def parse_result(self, response):
            imgdata = base64.b64decode(response.data['png'])
            filename = 'some_image.png'
            with open(filename, 'wb') as f:
                f.write(imgdata)
    

    【讨论】:

    • 非常感谢 - 非常有帮助!
    • 如果您不介意,还有一个问题是,您知道如何截取整个页面吗?我尝试将 render_all 设置为 True 作为 args 的一部分,但出现此错误:WARNING: Bad request to Splash: {'info': {'argument': 'render_all', 'type': 'bad_argument', 'description': "Pass non-zero 'wait' to render full webpage"}, 'type': 'BadOption', 'description': 'Incorrect HTTP API arguments', 'error': 400}
    • 我找到了解决方案 - 它是添加一个延迟,让完整的渲染发生!现在都整理好了,再次感谢您的帮助。
    • @ExamOrph 我应该在哪里以及如何添加延迟?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2021-12-26
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多