3 Easy Ways to Check Your Internet Speed in Python

5/5 - (1 vote)

Method 1: Speedtest-cli

To measure your Internet speed with Python, you can use the Speedtest-cli method. This Python library provides a command-line interface for testing internet bandwidth using speedtest.net. It performs a comprehensive test, providing download speed, upload speed, and latency data.

First, install the speedtest-cli library using:

pip install speedtest-cli

The following example can be used for copy and paste to check your Internet in Python: πŸ‘‡

import speedtest

st = speedtest.Speedtest()

print("Download Speed:", st.download())
print("Upload Speed:", st.upload())
print("Ping:", st.results.ping)

Here’s what this looks like in my Jupyter Notebook:

Method 2: Fast.com, Selenium, and BeautifulSoup

This method employs Selenium WebDriver and BeautifulSoup to automate a speed test using the Fast.com service, a platform provided by Netflix. It fetches the webpage, waits for the speed test to complete, and then extracts and returns the speed result.

Here’s an example:

from selenium import webdriver
from bs4 import BeautifulSoup
import time

def test_speed():
    driver = webdriver.Firefox()  # or webdriver.Chrome()
    driver.get('https://fast.com')
    time.sleep(60)  # Wait for test to complete
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    speed = soup.find('div', {'class': 'speed-results-container'}).text
    driver.quit()
    return speed

print("Internet speed: ", test_speed())

Method 3: Requests and Time

This method estimates internet speed by downloading a large file and recording the time it took to download. It uses the requests library to download the file, and the time library to measure the time elapsed. The speed is then the total file size divided by the time taken.

And the example:

import requests
import time

def check_speed(file_url):
    start_time = time.time()
    file = requests.get(file_url, stream=True)
    total_length = file.headers.get('content-length')
    if total_length is not None: 
        download_speed = int(total_length) / (time.time() - start_time)
        return download_speed

speed = check_speed("http://ipv4.download.thinkbroadband.com/5MB.zip")
print("Download Speed: ", speed)

Here’s the output of this code in my Jupyter notebook:

πŸ’‘ Recommended: Python Request Library