Amazing-Python-Scripts

Форк
0
70 строк · 2.0 Кб
1
import requests
2
import json
3
from responses import PageSpeedResponse
4

5

6
class PageSpeed(object):
7
    """
8
    Google PageSpeed analysis client
9

10
    Attributes:
11
        api_key (str): Optional API key for client account.
12
        endpoint (str): Endpoint for HTTP request
13
    """
14

15
    def __init__(self, api_key=None):
16
        self.api_key = api_key
17
        self.endpoint = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'
18

19
    def analyse(self, url, strategy='desktop', category='performance'):
20
        """
21
        Run PageSpeed test
22

23
        Args:
24
            url (str): The URL to fetch and analyse.
25
            strategy (str, optional): The analysis strategy to use. Acceptable values: 'desktop', 'mobile'
26
            category (str, optional): A Lighthouse category to run; if none are given, only Performance category will be run
27

28
        Returns:
29
            response: PageSpeed API results
30
        """
31
        strategy = strategy.lower()
32

33
        params = {
34
            'strategy': strategy,
35
            'url': url,
36
            'category': category,
37
        }
38

39
        if self.api_key:
40
            params['key'] = self.api_key
41

42
        # Sanity Check
43
        if strategy not in ('mobile', 'desktop'):
44
            raise ValueError('invalid strategy: {0}'.format(strategy))
45

46
        # Returns raw data
47
        raw = requests.get(self.endpoint, params=params)
48

49
        response = PageSpeedResponse(raw)
50

51
        return response
52

53
    def save(self, response, path='./'):
54
        json_data = response._json
55
        with open(path + "json_data.json", 'w+') as f:
56
            json.dump(json_data, f, indent=2)
57

58

59
if __name__ == "__main__":
60
    ps = PageSpeed()
61
    response = ps.analyse('https://www.example.com', strategy='mobile')
62
    ls = [
63
        response.url, response.loadingExperience,
64
        response.originLoadingExperience,
65
        response.originLoadingExperienceDetailed,
66
        response.loadingExperienceDetailed, response.finalUrl,
67
        response.requestedUrl, response.version, response.userAgent
68
    ]  # , response.lighthouseResults]
69
    ps.save(response)
70
    print(ls)
71

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.