This is a sample script for retrieving screen shots of sites using Google Apps Script. In order to retrieve the screen shot, here, I used PageSpeed API.
When you use this, please copy and paste the following script, and set an URL you want to retrieve a screen shot.
var siteUrl = "### URL you want to retrieve a screen shot. ###";
var url =
"https://www.googleapis.com/pagespeedonline/v4/runPagespeed?screenshot=true&fields=screenshot&url=" +
encodeURIComponent(siteUrl);
var res = UrlFetchApp.fetch(url).getContentText();
var obj = JSON.parse(res);
var blob = Utilities.newBlob(
Utilities.base64DecodeWebSafe(obj.screenshot.data),
"image/png",
"sample.png"
);
DriveApp.createFile(blob);
- Retrieved value of screen shot is a base64 data with Web Safe.
- In my environment, when I ran this script as a test, it was not required to enable this API at API console. And also I used no API key. If you want to retrieve values from a lot of URLs, it might be required to enable API and use API key.
Now, version 5 can be used. The script is as follows. In this case, please add the scope as the value of openid
. By this, the access token can be used. Although this sample script uses the access token, of course, you can also use the API key instead of the access token.
function myFunction() {
const siteUrl = "https://tanaikech.github.io/"; // Please set the site URL.
const url = `https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${encodeURIComponent(
siteUrl
)}&fields=${encodeURIComponent("lighthouseResult")}`;
const res = UrlFetchApp.fetch(url, {
muteHttpExceptions: true,
headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
});
const obj = JSON.parse(res.getContentText());
const base64 = obj["lighthouseResult"]["audits"]["final-screenshot"][
"details"
]["data"]
.split(",")
.pop();
const blob = Utilities.newBlob(
Utilities.base64Decode(base64),
"image/jpeg",
"sample1.jpg"
);
const id = DriveApp.createFile(blob).getId();
console.log(id);
}
- On January 30, 2024: I confirmed that the script of "Updated at December 9, 2021" worked.
I have to apologize for my poor English skill. I proposed the GAS library for retrieving the size from the image blob. When the image with the small size is expanding to the large size, the quality of the modified image is low.
By the way, when PageSpeed API is used, it seems that the image size is fixed and that cannot be created with the large size. This might be the specification.
When I want to retrieve the screen shot with the large size with Google Apps Script, I used the following script. But this cannot be used for all site. I apologize for this. I think that the reason of this is due to that Javascript might not be able to be used for this method.