|
| 1 | +import requests |
| 2 | + |
| 3 | +# Change the file name as per requirements. |
| 4 | +# |
| 5 | +with open('pagespeed.txt') as pagespeedurls: |
| 6 | + download_dir = 'pagespeed-results.csv' |
| 7 | + # Start writing the CSV file |
| 8 | + file = open(download_dir, 'w') |
| 9 | + content = pagespeedurls.readlines() |
| 10 | + content = [line.rstrip('\n') for line in content] |
| 11 | + # Populate Columns |
| 12 | + columnTitleRow = "URL, First Contentful Paint, First Interactive\n" |
| 13 | + file.write(columnTitleRow) |
| 14 | + |
| 15 | + # For loop for reading separate URLs from text file. |
| 16 | + for line in content: |
| 17 | + # Merging the Url from text file in order to successfully request from API |
| 18 | + # Strategy is an optional argument |
| 19 | + # It can be- |
| 20 | + """ |
| 21 | + "desktop": Fetch and analyze the URL for desktop browsers |
| 22 | + "mobile": Fetch and analyze the URL for mobile devices |
| 23 | + """ |
| 24 | + api_url = f'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url={line}&strategy=desktop' |
| 25 | + print(f'Requesting {api_url}...') |
| 26 | + r = requests.get(api_url) |
| 27 | + final = r.json() |
| 28 | + |
| 29 | + try: |
| 30 | + url_ID = final['id'] |
| 31 | + # This splits the absolute url from the api key parameter |
| 32 | + split = url_ID.split('?') |
| 33 | + # This reassigns url_ID to the absolute url |
| 34 | + url_ID = split[0] |
| 35 | + ID = f'URL ~ {url_ID}' |
| 36 | + ID2 = str(url_ID) |
| 37 | + urlfcp = final['lighthouseResult']['audits']['first-contentful-paint']['displayValue'] |
| 38 | + FCP = f'First Contentful Paint ~ {str(urlfcp)}' |
| 39 | + FCP2 = str(urlfcp) |
| 40 | + urlfi = final['lighthouseResult']['audits']['interactive']['displayValue'] |
| 41 | + FI = f'First Interactive ~ {str(urlfi)}' |
| 42 | + FI2 = str(urlfi) |
| 43 | + except KeyError: |
| 44 | + print(f'<KeyError> One or more keys not found {line}.') |
| 45 | + |
| 46 | + try: |
| 47 | + row = f'{ID2},{FCP2},{FI2}\n' |
| 48 | + file.write(row) |
| 49 | + except NameError: |
| 50 | + print(f'NameError in {line}.') |
| 51 | + file.write(f'Failing because of inconsistent key in {line}.' + '\n') |
| 52 | + |
| 53 | + try: |
| 54 | + print(ID) |
| 55 | + print(FCP) |
| 56 | + print(FI) |
| 57 | + except NameError: |
| 58 | + print(f'KeyError in {line}.') |
| 59 | + |
| 60 | + file.close() |
0 commit comments