Amazing-Python-Scripts
70 строк · 2.0 Кб
1import requests
2import json
3from responses import PageSpeedResponse
4
5
6class PageSpeed(object):
7"""
8Google PageSpeed analysis client
9
10Attributes:
11api_key (str): Optional API key for client account.
12endpoint (str): Endpoint for HTTP request
13"""
14
15def __init__(self, api_key=None):
16self.api_key = api_key
17self.endpoint = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'
18
19def analyse(self, url, strategy='desktop', category='performance'):
20"""
21Run PageSpeed test
22
23Args:
24url (str): The URL to fetch and analyse.
25strategy (str, optional): The analysis strategy to use. Acceptable values: 'desktop', 'mobile'
26category (str, optional): A Lighthouse category to run; if none are given, only Performance category will be run
27
28Returns:
29response: PageSpeed API results
30"""
31strategy = strategy.lower()
32
33params = {
34'strategy': strategy,
35'url': url,
36'category': category,
37}
38
39if self.api_key:
40params['key'] = self.api_key
41
42# Sanity Check
43if strategy not in ('mobile', 'desktop'):
44raise ValueError('invalid strategy: {0}'.format(strategy))
45
46# Returns raw data
47raw = requests.get(self.endpoint, params=params)
48
49response = PageSpeedResponse(raw)
50
51return response
52
53def save(self, response, path='./'):
54json_data = response._json
55with open(path + "json_data.json", 'w+') as f:
56json.dump(json_data, f, indent=2)
57
58
59if __name__ == "__main__":
60ps = PageSpeed()
61response = ps.analyse('https://www.example.com', strategy='mobile')
62ls = [
63response.url, response.loadingExperience,
64response.originLoadingExperience,
65response.originLoadingExperienceDetailed,
66response.loadingExperienceDetailed, response.finalUrl,
67response.requestedUrl, response.version, response.userAgent
68] # , response.lighthouseResults]
69ps.save(response)
70print(ls)
71