How to Track Core Web Vitals Over Time with Python

Tracking Core Web Vitals Over Time with Python

As a web developer, you want to ensure that your website provides an optimal user experience. One way to achieve this is by tracking the performance of your site using the Core Web Vitals (CWV) metrics provided by Google. In this article, we’ll explore how to track CWVs over time using Python.

What are Core Web Vitals?

Core Web Vitals are a set of metrics that measure the performance of a website on desktop and mobile devices. They include:

  • Largest Contentful Paint (LCP): The time it takes for the main content of a page to load.
  • First Input Delay (FID): The time it takes for a user to interact with a page, such as clicking a button or entering text into a form field.
  • Cumulative Layout Shift (CLS): The total amount of unexpected layout shifts that occur on a page.

Why Track CWVs Over Time?

Tracking CWVs over time allows you to:

  • Monitor the performance of your website and identify areas for improvement.
  • Set goals and targets for improving your site’s performance.
  • Compare your site’s performance with industry benchmarks and best practices.
  • Identify trends and patterns in your site’s performance over time.

How to Track CWVs Over Time using Python

To track CWVs over time, we’ll use the following tools:

  • python-dateutil: A library for working with dates and times.
  • requests: A library for making HTTP requests.
  • pandas: A library for data manipulation and analysis.

Step 1: Install Required Libraries

First, install the required libraries using pip:

bash
pip install python-dateutil requests pandas

Step 2: Get CWV Data from Google

To get CWV data from Google, you’ll need to use the Google Analytics API. You can do this by following these steps:

  1. Create a new project in the Google Cloud Console.
  2. Enable the Google Analytics API.
  3. Create credentials for your project (OAuth client ID).
  4. Install the google-auth and google-api-python-client libraries using pip.

Here’s an example of how to get CWV data from Google:

“`python
import requests
from datetime import datetime, timedelta

def get_cwv_data(api_key, start_date, end_date):
url = f”https://analyticsreporting.googleapis.com/v4/reports?keys=ga:users&metrics=ga:users&startDate={start_date}&endDate={end_date}”

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json; charset=UTF-8"
}

response = requests.post(url, headers=headers)

return response.json()

Get CWV data for the past 30 days

start_date = (datetime.now() – timedelta(days=30)).strftime(“%Y-%m-%d”)
end_date = datetime.now().strftime(“%Y-%m-%d”)

api_key = “YOUR_API_KEY_HERE”

cwv_data = get_cwv_data(api_key, start_date, end_date)

Print CWV data

print(cwv_data)
“`

Step 3: Store and Analyze CWV Data

To store and analyze CWV data, you can use a database like SQLite. Here’s an example of how to store CWV data in a SQLite database:

“`python
import sqlite3
import pandas as pd

Create a SQLite connection

conn = sqlite3.connect(“cwv_data.db”)

Create a table for storing CWV data

c = conn.cursor()

c.execute(“””CREATE TABLE IF NOT EXISTS cwv_data (
id INTEGER PRIMARY KEY,
date TEXT,
lcp REAL,
fid REAL,
cls REAL
)”””)

Store CWV data in the database

for row in cwv_data[“rows”]:
c.execute(“INSERT INTO cwv_data (date, lcp, fid, cls) VALUES (?, ?, ?, ?)”,
(row[0][“dimensions”][“DATE”], row[1], row[2], row[3]))

Commit changes to the database

conn.commit()

Close the SQLite connection

conn.close()
“`

Step 4: Visualize CWV Data

To visualize CWV data, you can use a library like Matplotlib or Seaborn. Here’s an example of how to create a line chart using Matplotlib:

“`python
import matplotlib.pyplot as plt

Create a figure and axis object

fig, ax = plt.subplots()

Load CWV data from the database

conn = sqlite3.connect(“cwv_data.db”)
c = conn.cursor()
c.execute(“SELECT * FROM cwv_data”)
rows = c.fetchall()
conn.close()

Extract date and CWV values from the rows

dates = [row[1] for row in rows]
lcp_values = [row[2] for row in rows]

Create a line chart of LCP values over time

ax.plot(dates, lcp_values)

Set title and labels for the axes

ax.set_title(“LCP Values Over Time”)
ax.set_xlabel(“Date”)
ax.set_ylabel(“LCP Value”)

Show the plot

plt.show()
“`

This is a basic example of how to track CWVs over time using Python. You can customize this code to suit your specific needs and add more features as required.

Conclusion

Tracking Core Web Vitals (CWVs) over time allows you to monitor the performance of your website, identify areas for improvement, set goals and targets, compare your site’s performance with industry benchmarks, and identify trends and patterns in your site’s performance over time. In this article, we’ve explored how to track CWVs over time using Python, including getting CWV data from Google, storing and analyzing CWV data, and visualizing CWV data.

By following the steps outlined in this article, you can create a system for tracking CWVs over time and use this data to improve the performance of your website.