Untitled

 avatar
unknown
plain_text
a year ago
1.9 kB
3
Indexable
import time
from speedtest import Speedtest
import re
import requests
from bs4 import BeautifulSoup

def get_packet_loss_from_url(url):
    try:
        response = requests.get(url)
        soup = BeautifulSoup(response.content, 'html.parser')
        packet_loss_element = soup.find("div", {"id": "result-packetloss"})
        if packet_loss_element:
            return float(re.search(r'(\d+)%', packet_loss_element.get_text()).group(1))
        return None
    except:
        return None

def test_speed():
    st = Speedtest()
    
    # Get the best server based on ping
    st.get_best_server()
    
    # Get the download and upload speeds in bits per second
    download_speed = st.download()
    upload_speed = st.upload()
    
    # Convert bits per second to megabits per second
    download_speed_mbps = round(download_speed / 1_000_000, 2)
    upload_speed_mbps = round(upload_speed / 1_000_000, 2)

    # Get packet loss
    result_url = st.results.share()
    packet_loss = get_packet_loss_from_url(result_url)
    latency = st.results.ping
    
    return download_speed_mbps, upload_speed_mbps, packet_loss, latency

def main():
    while True:
        try:
            download, upload, packet_loss, latency = test_speed()
            timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            
            with open("internet_speed_log.txt", "a") as f:
                f.write(f"{timestamp} - Download: {download} Mbps, Upload: {upload} Mbps, Packet Loss: {packet_loss}%, Latency: {latency} ms\n")
                
            print(f"Logged speed at {timestamp}")
            time.sleep(1*60)  # Wait for 10 minutes

        except Exception as e:
            print(f"An error occurred: {e}")
            time.sleep(30)  # If there's an error, wait for a minute before trying again

if __name__ == '__main__':
    main()