Google PageSpeed Insights API截图存档


Google PageSpeed Insights API Screenshot to file

我一直试图从API检索屏幕截图,但当我解码并保存图像时,我得到了一个损坏的图像。下面是我正在使用的代码。如果你想测试的话,我为一个包含谷歌响应的样本文件创建了一个tinyurl

$name = 'test';
$result = file_get_contents('http://tinyurl.com/q4smyod'); 
$result = json_decode($result, true);
$decoded=base64_decode($result['screenshot']['data']);
file_put_contents('img/'.$name.'.jpg',$decoded);

正如我在评论中提到的,这个问题是由使用phpapi时谷歌加密的错误引起的。如果您遇到此问题,只需使用以下替换函数来修复编码。

$data    = str_replace('_','/',$result['screenshot']['data']);
$data    = str_replace('-','+',$data);
$decoded = base64_decode($data);

这将帮助您更接近目标。您没有定义名称,并且您的json_edding有点奇怪:

<?php
     error_reporting(-1);
     ini_set('display_errors', 'On');
     $result = file_get_contents('http://tinyurl.com/q4smyod'); 
     $name = 'test2';
     $result = json_decode($result, true);
     $decoded = base64_encode($result['screenshot']['data']);
     file_put_contents($name.'.jpg',$decoded);
?>

目前我正在使用Google Page Speed API通过Web URL捕获图像并将其保存到我指定的位置。这样做没有任何问题。请看一看。评论易于理解。

import urllib2
import json
import base64
import sys
import requests
import os
import errno
#   The website's URL as an Input
site = #specify the URL here
imagePath = #specify your path to save the image
#   The Google API.  Remove "&strategy=mobile" for a desktop screenshot
api = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?screenshot=true&strategy=mobile&url=" + urllib2.quote(site)
#   Get the results from Google
try:
    site_data = json.load(urllib2.urlopen(api))
except urllib2.URLError:
    print "Unable to retreive data"
    sys.exit()
try:
    screenshot_encoded =  site_data['screenshot']['data']
except ValueError:
    print "Invalid JSON encountered."
    sys.exit()
#   Google has a weird way of encoding the Base64 data
screenshot_encoded = screenshot_encoded.replace("_", "/")
screenshot_encoded = screenshot_encoded.replace("-", "+")
#   Decode the Base64 data
screenshot_decoded = base64.b64decode(screenshot_encoded)
if not os.path.exists(os.path.dirname(impagepath)):
    try:
        os.makedirs(os.path.dirname(impagepath))
        except  OSError as exc:
            if exc.errno  != errno.EEXIST:
                raise
#   Save the file
with open(imagePath, 'w') as file_:
    file_.write(screenshot_decoded)