Have you ever visited a website and it felt slow to load? As a developer, being able to measure page load times is crucial for providing a good user experience. Python makes this easy with the requests module.
In this article, I'll walk through a simple script to fetch a webpage and calculate how long it takes to fully load.
Fetching a Page with Requests
First, we need to install
pip install requests
Then we can fetch a page. Let's try example.com:
import requests
response = requests.get('https://example.com')
This sends a GET request to the URL and saves the Response object to
Timing Page Load
Now we can use Python's time module to measure how long the request took:
import time
start_time = time.time()
response = requests.get('https://example.com')
end_time = time.time()
duration = end_time - start_time
print(f"Page loaded in {duration} seconds")
We record the start time before making the request, and the end time after. By subtracting them, we get the total duration.
On my machine, example.com loaded in 0.58 seconds. That's pretty fast!
Going Further
There's a lot more we could do:
Measuring page load times helps find performance issues. Slow sites lead to unhappy users, so keep your pages speedy!