Recording Page Load Time with Pytest and Saving to CSV
Automatically Track the Page Load Time for Performance checking
Tracking page load performance is a critical part of maintaining a fast and user-friendly website. In this tutorial, we will use pytest
and Python’s built-in tools to measure how long a page takes to load and save the results to a CSV file. Each row in the CSV will include a timestamp and the corresponding load time.
What You Need
pytest
requests
datetime
andcsv
from the standard library
The Code
This code fetches a web page, measures the response time, and logs the result with a timestamp to a CSV file.
import pytest
import requests
import time
import csv
from datetime import datetime
URL_TO_TEST = "https://www.americanfreight.com/"
CSV_FILE = "page_load_times.csv"
def write_to_csv(timestamp, load_time):
"""Append timestamp and load time to the CSV file."""
with open(CSV_FILE, mode="a", newline="") as file:
writer = csv.writer(file)
writer.writerow([timestamp, load_time])
@pytest.mark.parametrize("url", [URL_TO_TEST])
def test_page_load_time(url):
"""Measure the page load time and write to a CSV file."""
start_time = time.time()
response = requests.get(url)
end_time = time.time()
load_time = round(end_time - start_time, 3)
timestamp = datetime.now().isoformat(timespec="seconds")
assert response.status_code == 200, f"Failed to load page: {response.status_code}"
write_to_csv(timestamp, load_time)
print(f"Page loaded in {load_time} seconds at {timestamp}")
Sample CSV Output
Here is what the CSV file will look like after a few test runs:
2025-05-21T13:00:01,1.276
2025-05-21T13:10:43,1.304
2025-05-21T13:20:22,1.142
Automating in CI
You can easily integrate this into your CI pipeline to monitor page load performance over time. Combine it with cron jobs or GitHub Actions to schedule regular runs and keep tabs on performance degradation.
Tips
- Use
requests.Session()
for persistent connections if testing multiple pages. - Extend the CSV format to include response size or headers if needed.
- Visualize the results using tools like Excel or Python’s
matplotlib
.
Conclusion
Measuring and recording page load times with pytest
is simple yet powerful. With just a few lines of code, you can start building a performance history and catching slowdowns before they impact your users.