python - Scrapy Splash 截图?

标签 python lua scrapy scrapy-splash

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

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 可以做到这一点,但一直无法找到实现这一点的方法。谢谢。

最佳答案

你从 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)

关于python - Scrapy Splash 截图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45172260/

相关文章:

python - heroku 不支持 django 应用程序并引发错误

lua - Lua中doFile和require有什么区别

recursion - 重置递归 Lua 函数中的变量

python - Scrapy 不会抓取所有页面

python - 如何从 python 脚本结果中删除 u''?

python - 如何使用OpenCV在几乎圆形的孔中找到各种圆弧的不同中心?

python - 在用 Python 编写的列表中搜索列表

python - 了解使用二分法找到解决方案的迭代次数

lua - 电晕停止对象被拖出屏幕

python - Scrapy递归链接爬虫