使用googlepagespeed api

时间:2018-11-12 10:40:40

标签: php google-api

下面是我的代码,用于捕获网页的屏幕截图。但是我得到的输出与下图中的输出相同。请提出我犯的错误是什么。还建议将屏幕截图保存到服务器的方法?

enter image description here

<?php
 $url='https://www.google.com';
 $stratedy = 'mobile' ;
 $apiReqUrl = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed';
 $apiKey = 'my_api_key' ;
 $curl = curl_init();
 curl_setopt($curl, CURL_OPTURL, $apiReqUrl.'?url='.$reqUrl.' 
 &key='.$apiKey.'&screenshot=true&strategy='.$stratedy);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
 $result=curl_exec($curl);
 $data = json_decode($result, true);
 $img = str_replace(array('_','-'), array('/','+'), $data['screenshot'] 
 ['data']);
 echo '<img src="data:image/jpeg;base64,'.$img.'">';
 ?>

1 个答案:

答案 0 :(得分:1)

如果可以,请尝试使用Generating Screenshots of URLs using Google's secret magic API中的HTML版本。您所需要做的就是调用该API,并且它是免费的(我想)。

例如在PHP中:

<?php  

$url = "https://praveen.science/";

// Hit the Google PageSpeed Insights API.
// Catch: Your server needs to allow file_get_contents() to make this run. Or you need to use cURL.
$response = file_get_contents('https://www.googleapis.com/pagespeedonline/v2/runPagespeed?screenshot=true&url='.urlencode($url));

// Convert the JSON response into an array.
$googlePagespeedObject = json_decode($response, true);

// Grab the Screenshot data.
$screenshot = $googlePagespeedObject['screenshot']['data'];

// Fix url encoded base64
$screenshot = str_replace(array('_','-'), array('/','+'), $screenshot);

// Build the Data URI scheme and spit out an <img /> Tag.
echo "<img src=\"data:image/jpeg;base64,{$screenshot}\" alt=\"Screenshot\" />";

// Or.. base64 decode and store
file_put_contents('...', base64_decode($screenshot));

或使用JavaScript:

$(function() {
  // Get the URL.
  var url = "https://praveen.science/";
  // Prepare the URL.
  url = encodeURIComponent(url);
  // Hit the Google Page Speed API.
  $.get("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?screenshot=true&strategy=mobile&url=" + url, function(data) {
    // Get the screenshot data.
    var screenshot = data.screenshot;
    // Convert the Google's Data to Data URI scheme.
    var imageData = screenshot.data.replace(/_/g, "/").replace(/-/g, "+");
    // Build the Data URI.
    var dataURI = "data:" + screenshot.mime_type + ";base64," + imageData;
    // Set the image's source.
    $("img").attr("src", dataURI);
  });
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<h1>Hard Coded Screenshot of my Website:</h1>
<img src="//placehold.it/300x50?text=Loading+Screenshot..." alt="Screenshot" />