Use the requests
library to fetch the webpage and measure the time taken from sending the request to receiving the response.
- Use the
time
library to record the time to calculate the total load time.
Example Script
import requests
import time
def measure_load_time(url):
try:
# Record the start time
start_time = time.time()
# Send GET request to fetch the page
response = requests.get(url)
# Record the end time
end_time = time.time()
# Calculate the load time
load_time = end_time - start_time
# Check if the page was successfully loaded
if response.status_code == 200:
print(f"Site {url} opened successfully, Status Code: {response.status_code}")
else:
print(f"Failed to load site {url}, Status Code: {response.status_code}")
print(f"Load time for {url}: {load_time:.2f} seconds")
return load_time
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return None
# List of site URLs to test
urls = [
"https://www.google.com",
"https://www.github.com",
"https://www.example.com",
# You can add more URLs here
]
# Test the load speed of each site
for url in urls:
measure_load_time(url)
Key Parts Explained:
requests.get(url)
: This sends an HTTP GET request to load the webpage content. Therequests
library automatically handles redirections and other HTTP operations.time.time()
: This is used to record the current timestamp (in seconds), which helps calculate the time difference between the start and end of the request.- Status Code Check: The script checks the returned HTTP status code to ensure the page was successfully loaded (status code 200 indicates success).
- Exception Handling:
requests.exceptions.RequestException
is used to catch potential network errors or connection issues.
How to Run the Script:
- Save the Script: Save the above code to a file, for example,
site_speed_test.py
. - Run the Script: Use the following command in the terminal to run the script:
python3 site_speed_test.py
- View the Results: The script will output the load time for each site (in seconds) along with the HTTP status code.
Notes:
- Network Environment: The test results will be influenced by your current network conditions. If the network connection is slow, the load times will be longer.
- Page Size and Complexity: Large or complex pages typically take longer to load. The script measures just the initial HTTP response time, not the time required to load all resources (like images, scripts, etc.).
Extensions:
- Measure Full Load Time: If you want to measure the complete load time of a page, including all resources (like images, CSS, JavaScript), you can use
Selenium
for more precise measurement. - Concurrent Testing: Use
concurrent.futures
orasyncio
for concurrent testing to increase efficiency, especially if you need to test multiple sites. - Save Results: You can save the results to a CSV or JSON file for further analysis.