Managing a website on your own is no small feat, and tracking PageSpeed Insights performance reports for each page manually can be incredibly tedious.
Luckily, automation can save the day!
In my search for a solution, I stumbled upon the Google PageSpeed Insights API, a tool that can automate the retrieval of performance data.
However, finding straightforward guidance on how to use it was challenging—most tutorials I encountered were either overwhelming or unclear.
That’s when I turned to ChatGPT, which helped me navigate through the trial and error.
Now, I’m here to make things simpler for you.
In this guide, I’ll walk you through the process, from setting up your Google Cloud project to running the code in Google Colab.
What Does This Script Do?
The script retrieves performance data for both mobile and desktop versions of the pages you specify.
By the end of this guide, you’ll have a fully automated solution to track your website’s performance with ease.
If this is what you need, continue this blog.
What You’ll Need
- A Google Cloud account
- Access to Google Colab
Step 1: Set Up Your Google Cloud Project and Enable APIs
1. Create a Google Cloud Project:
- Go to the Google Cloud Console.
- Create a new project.
2. Enable the PageSpeed Insights API:
- In your Google Cloud project, navigate to the API & Services dashboard.
- Search for “PageSpeed Insights API” and enable it.
3. Create API Credentials:
- Go to the Credentials tab in the API & Services dashboard.
- Click on Create Credentials and select API Key.
- Copy the generated API key; you’ll need it later.
Step 2: Open Google Colab
1. Access Google Colab:
- Go to Google Colab.
- Sign in with your Google account if you haven’t already.
2. Create a New Notebook:
- Click on New Notebook to create a new Python notebook.
3. Install Required Libraries:
- Google Colab comes pre-installed with many popular libraries, including
requests
. However, if you need to install any additional libraries, use the following command:
!pip install requests
Step 3: Implement the Script
Now, copy and paste the script below into a code cell in your Colab notebook:
import requests
def get_pagespeed_insights(api_key, urls, strategy='mobile'):
base_url = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'
performance_scores = []
for url in urls:
params = {
'url': url,
'key': api_key,
'strategy': strategy
}
response = requests.get(base_url, params=params)
data = response.json()
if 'error' in data:
print(f"Error for URL {url}: {data['error']['message']}")
continue
performance_score = data['lighthouseResult']['categories'].get('performance', {}).get('score', 0) * 100
performance_scores.append({'url': url, 'performance_score': performance_score})
return performance_scores
# Replace 'YOUR_API_KEY' with your actual PageSpeed Insights API key
api_key = 'YOUR_API_KEY'
# List of URLs for which you want to retrieve PageSpeed Insights
url_list = ['https://www.example1.com/', 'https://www.example2.com/', 'https://www.example3.com/',
'https://www.exampl42.com/']
# Get performance data for mobile
mobile_performance_scores = get_pagespeed_insights(api_key, url_list, strategy='mobile')
# Get performance data for desktop
desktop_performance_scores = get_pagespeed_insights(api_key, url_list, strategy='desktop')
# Display the performance scores
print("Mobile Performance Scores:")
for result in mobile_performance_scores:
print(f" {result['performance_score']}")
print("\nDesktop Performance Scores:")
for result in desktop_performance_scores:
print(f" {result['performance_score']}")
Step 4: Run the Script and Retrieve the Output
After running the script, you’ll get the performance scores for both mobile and desktop.
You can then copy and paste this data into a spreadsheet near each URL for easy tracking.
Customization Options
If copying the data manually isn’t your style, you can modify the script to output the data into a CSV file or explore other methods to suit your needs.
The flexibility of this script allows for plenty of customization based on the scope of your project.