├── pagespeed ├── __init__.py ├── pagespeed.py └── responses.py ├── tests.py ├── README.md ├── LICENSE └── .gitignore /pagespeed/__init__.py: -------------------------------------------------------------------------------- 1 | from pagespeed.pagespeed import PageSpeed -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | import pagespeed 2 | 3 | p = pagespeed.PageSpeed() 4 | 5 | r = p.analyse('https://www.example.com', strategy='desktop') 6 | 7 | print(r.speed) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Google PageSpeed Insights for Python 2 | 3 | [![Packagist](https://img.shields.io/packagist/l/doctrine/orm.svg)]() 4 | 5 | `pagespeed` offers a convenient interface for the Google PageSpeed Insights API. 6 | It is written in Python and provides an easy way to query a site's page speed. 7 | 8 | ## Quickstart 9 | Execute a query with: 10 | 11 | ```python 12 | import pagespeed 13 | 14 | ps = pagespeed.PageSpeed() 15 | response = ps.analyse('https://www.example.com', strategy='desktop') 16 | print(response.speed) 17 | ``` 18 | 19 | ## Note 20 | This is for Version 2 of the Google PageSpeed Insights API. The most recent version 21 | is Version 4. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Josh Carty 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | /pagespeed.pyproj 3 | /pagespeed/__pycache__ 4 | /.vs/pagespeed/v14 5 | /pagespeed.sln 6 | ### Python template 7 | # Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | env/ 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | wheels/ 30 | *.egg-info/ 31 | .installed.cfg 32 | *.egg 33 | 34 | # PyInstaller 35 | # Usually these files are written by a python script from a template 36 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 37 | *.manifest 38 | *.spec 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *,cover 53 | .hypothesis/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | target/ 75 | 76 | # Jupyter Notebook 77 | .ipynb_checkpoints 78 | 79 | # pyenv 80 | .python-version 81 | 82 | # celery beat schedule file 83 | celerybeat-schedule 84 | 85 | # SageMath parsed files 86 | *.sage.py 87 | 88 | # dotenv 89 | .env 90 | 91 | # virtualenv 92 | .venv 93 | venv/ 94 | ENV/ 95 | 96 | # Spyder project settings 97 | .spyderproject 98 | 99 | # Rope project settings 100 | .ropeproject 101 | 102 | .DS_Store 103 | -------------------------------------------------------------------------------- /pagespeed/pagespeed.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from pagespeed.responses import DesktopPageSpeed, MobilePageSpeed 3 | 4 | 5 | class PageSpeed(object): 6 | """Google PageSpeed analysis client 7 | 8 | Attributes: 9 | api_key (str): Optional API key for client account. 10 | endpoint (str): Endpoint for HTTP request 11 | """ 12 | 13 | def __init__(self, api_key=None): 14 | self.api_key = api_key 15 | self.endpoint = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed' 16 | 17 | def analyse(self, url, filter_third_party_resources=False, screenshot=False, 18 | strategy='desktop'): 19 | """Run PageSpeed test 20 | 21 | Args: 22 | url (str): The URL to fetch and analyse. 23 | filter_third_party_resources (bool, optional): Indicates if third party 24 | resources should be filtered out before PageSpeed analysis. (Default: false) 25 | locale (str, optional): The locale used to localize formatted results. 26 | rule (list, optional): A PageSpeed rule to run; if none are given, all rules are run 27 | screenshot (bool, optional): Indicates if binary data containing a screenshot should 28 | be included (Default: false) 29 | strategy (str, optional): The analysis strategy to use. Acceptable values: 'desktop', 'mobile' 30 | 31 | """ 32 | 33 | params = { 34 | 'filter_third_party_resources': filter_third_party_resources, 35 | 'screenshot': screenshot, 36 | 'strategy': strategy, 37 | 'url': url 38 | } 39 | 40 | strategy = strategy.lower() 41 | if strategy not in ('mobile', 'desktop'): 42 | raise ValueError('invalid strategy: {0}'.format(strategy)) 43 | 44 | raw = requests.get(self.endpoint, params=params) 45 | 46 | if strategy == 'mobile': 47 | response = MobilePageSpeed(raw) 48 | else: 49 | response = DesktopPageSpeed(raw) 50 | 51 | return response -------------------------------------------------------------------------------- /pagespeed/responses.py: -------------------------------------------------------------------------------- 1 | class Response(object): 2 | """ Base Response Object 3 | 4 | Attributes: 5 | self.json (dict): JSON representation of response 6 | self._request (str): URL of 7 | self._response (`requests.models.Response` object): Response object from requests module 8 | """ 9 | def __init__(self, response): 10 | response.raise_for_status() 11 | 12 | self._response = response 13 | self._request = response.url 14 | self.json = response.json() 15 | 16 | def __repr__(self): 17 | return '' 18 | 19 | 20 | class PageSpeedResponse(Response): 21 | """ PageSpeed Response Object 22 | 23 | Attributes: 24 | self.url (str): 25 | self.title (str): 26 | self.locale (str): 27 | self.version (str): 28 | self.speed (int): 29 | self.statistics (`Statistics` object): 30 | """ 31 | 32 | @property 33 | def url(self): 34 | return self.json.get('id') 35 | 36 | @property 37 | def title(self): 38 | return self.json.get('title') 39 | 40 | @property 41 | def locale(self): 42 | return self.json.get('formattedResults').get('locale') 43 | 44 | @property 45 | def version(self): 46 | major = self.json.get('version').get('major') 47 | minor = self.json.get('version').get('minor') 48 | return '{0}.{1}'.format(major, minor) 49 | 50 | @property 51 | def speed(self): 52 | return self.json.get('ruleGroups').get('SPEED').get('score') 53 | 54 | @property 55 | def statistics(self): 56 | page_stats = self.json.get('pageStats') 57 | return Statistics(page_stats) 58 | 59 | def to_csv(self, path): 60 | pass 61 | 62 | def pretty_print(self): 63 | pass 64 | 65 | def __repr__(self): 66 | return ''.format(self.url) 67 | 68 | 69 | class DesktopPageSpeed(PageSpeedResponse): 70 | 71 | def __repr__(self): 72 | return ''.format(self.url) 73 | 74 | 75 | class MobilePageSpeed(PageSpeedResponse): 76 | 77 | @property 78 | def usability(self): 79 | return self.json.get('ruleGroups').get('USABILITY').get('score') 80 | 81 | def __repr__(self): 82 | return ''.format(self.url) 83 | 84 | 85 | class Statistics(object): 86 | def __init__(self, page_stats): 87 | self.page_stats = page_stats 88 | 89 | @property 90 | def css_response_bytes(self): 91 | return self.page_stats.get('cssResponseBytes') 92 | 93 | @property 94 | def html_response_bytes(self): 95 | return self.page_stats.get('htmlResponseBytes') 96 | 97 | @property 98 | def image_response_bytes(self): 99 | return self.page_stats.get('imageResponseBytes') 100 | 101 | @property 102 | def javascript_response_bytes(self): 103 | return self.page_stats.get('javascriptResponseBytes') 104 | 105 | @property 106 | def number_css_resources(self): 107 | return self.page_stats.get('numberCssResources') 108 | 109 | @property 110 | def number_hosts(self): 111 | return self.page_stats.get('numberHosts') 112 | 113 | @property 114 | def number_js_resources(self): 115 | return self.page_stats.get('numberJsResources') 116 | 117 | @property 118 | def number_resources(self): 119 | return self.page_stats.get('numberResources') 120 | 121 | @property 122 | def number_static_resources(self): 123 | return self.page_stats.get('numberStaticResources') 124 | 125 | @property 126 | def other_response_bytes(self): 127 | return self.page_stats.get('otherResponseBytes') 128 | 129 | @property 130 | def text_response_bytes(self): 131 | return self.page_stats.get('textResponseBytes') 132 | 133 | @property 134 | def total_request_bytes(self): 135 | return self.page_stats.get('totalRequestBytes') --------------------------------------------------------------------------------