Page Speed API
October 29, 2022
Page Speed Script:
import requests
import json
from responses import PageSpeedResponse
# http://www.pillalamarri.in/python/page-speed-api/
class PageSpeed(object):
"""
Google PageSpeed analysis client
Attributes:
api_key (str): Optional API key for client account.
endpoint (str): Endpoint for HTTP request
"""
def __init__(self, api_key=None):
self.api_key = api_key
self.endpoint = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'
def analyse(self, url, strategy='desktop', category='performance'):
"""
Run PageSpeed test
Args:
url (str): The URL to fetch and analyse.
strategy (str, optional): The analysis strategy to use. Acceptable values: 'desktop', 'mobile'
category (str, optional): A Lighthouse category to run; if none are given, only Performance category will be run
Returns:
response: PageSpeed API results
"""
strategy = strategy.lower()
params = {
'strategy': strategy,
'url': url,
'category': category,
}
if self.api_key:
params['key'] = self.api_key
# Sanity Check
if strategy not in ('mobile', 'desktop'):
raise ValueError('invalid strategy: {0}'.format(strategy))
# Returns raw data
raw = requests.get(self.endpoint, params=params)
response = PageSpeedResponse(raw)
return response
def save(self, response, path='./'):
json_data = response._json
with open(path + "json_data.json", 'w+') as f:
json.dump(json_data, f, indent=2)
# http://www.pillalamarri.in/python/page-speed-api/
if __name__ == "__main__":
ps = PageSpeed()
response = ps.analyse('https://www.example.com', strategy='mobile')
ls = [
response.url, response.loadingExperience,
response.originLoadingExperience,
response.originLoadingExperienceDetailed,
response.loadingExperienceDetailed, response.finalUrl,
response.requestedUrl, response.version, response.userAgent
] # , response.lighthouseResults]
ps.save(response)
print(ls)
Response Script:
import json
# http://www.pillalamarri.in/python/page-speed-api/
class Response(object):
"""
Base Response Object
Attributes:
self.json (dict): JSON representation of response
self._request (str): URL of
self._response (`requests.models.Response` object): Response object from requests module
"""
def __init__(self, response):
response.raise_for_status()
self._response = response
self._request = response.url
self._json = json.loads(response.content)
class PageSpeedResponse(Response):
"""
PageSpeed Response Object
Attributes:
self.url (str):
self.speed (int):
self.statistics (`Statistics` object):
"""
@property
def url(self):
return self._json['id']
@property
def loadingExperience(self):
return self._json['loadingExperience']['overall_category']
@property
def originLoadingExperience(self):
return self._json['originLoadingExperience']['overall_category']
@property
def originLoadingExperienceDetailed(self):
metrics = self._json['originLoadingExperience']['metrics']
keys_ = list(metrics.keys())
originLoadingExperienceDetailed_ = {}
for each in keys_:
originLoadingExperienceDetailed_[each] = metrics[each]['category']
return originLoadingExperienceDetailed_
@property
def loadingExperienceDetailed(self):
metrics = self._json['loadingExperience']['metrics']
keys_ = list(metrics.keys())
loadingExperienceDetailed_ = {}
for each in keys_:
loadingExperienceDetailed_[each] = metrics[each]['category']
return loadingExperienceDetailed_
# In case of re-directs
@property
def requestedUrl(self):
return self._json['lighthouseResult']['requestedUrl']
@property
def finalUrl(self):
return self._json['lighthouseResult']['finalUrl']
@property
def version(self):
return self._json['lighthouseResult']['lighthouseVersion']
@property
def userAgent(self):
return self._json['lighthouseResult']['userAgent']
@property
def lighthouseResults(self):
return self._json['lighthouseResult']
# http://www.pillalamarri.in/python/page-speed-api/
Test Script:
import pagespeed
from pagespeed import PageSpeed
# http://www.pillalamarri.in/python/page-speed-api/
ps = PageSpeed()
response = ps.analyse('https://www.example.com', strategy='mobile')
ls = [
response.url, response.loadingExperience, response.originLoadingExperience,
response.originLoadingExperienceDetailed,
response.loadingExperienceDetailed, response.finalUrl,
response.requestedUrl, response.version, response.userAgent
] # , response.lighthouseResults]
ps.save(response)
print(ls)
# http://www.pillalamarri.in/python/page-speed-api/
Posted in Python