我试图在抓取每个页面的屏幕截图的同时抓取一个网站。到目前为止,我已经成功地拼凑了以下代码:
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可以做到这一点,但一直无法找到实现这一点的方法。谢谢。
发布于 2017-07-19 00:41:33
你从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)https://stackoverflow.com/questions/45172260
复制相似问题