DEV Community

Discussion on: Covid19 live tracker

Collapse
 
thewils_alan profile image
Alan Wilson

Sorry, since it didn't work out of the box for me - I was running Python 2.7.17 - I had to play around with it for a while to remove the syntax errors...and...well, one thing led to another :) Still, I learned quite a bit here including how to post code. Never done anything in python before so here goes (without my comments to keep the code clean):

import requests
import bs4

def covid19(country):
    res = requests.get("https://www.worldometers.info/coronavirus/#countries")
    soup = bs4.BeautifulSoup(res.text, 'lxml')
    data=soup.select('tr td')

    index = find_country(data,country)

    if index == -1:
        print("This country does not exist\n\n")
    else:
        Dict = load_country_data(data, index)
        print_country_data(Dict)

def find_country(data, country):
    if country.lower() == "world":
        country = "Total:"

    for i in range(len(data)):
        if data[i].text.lower()==country.lower():
            return i
    return -1

def load_country_data(data, index):
    Dict = {'name': data[index].text,
            'tot_cases': get_int(data[index+1].text),
            'new_cases': get_int(data[index+2].text),
            'tot_deaths': get_int(data[index+3].text),
            'new_deaths': get_int(data[index+4].text),
            'recovered': get_int(data[index+5].text),
            'active': get_int(data[index+6].text)}
    return Dict

def print_country_data(country_data):
    print("Found \n")
    print(country_data['name'])
    print('=' * len(country_data['name']))

    print("Total Cases    : {0:9,d}".format(country_data['tot_cases']))
    print("New   Cases    : {0:+9,d}".format(country_data['new_cases']))

    print("Total Deaths   : {0:9,d}".format(country_data['tot_deaths']))
    print("New   Deaths   : {0:+9,d}".format(country_data['new_deaths']))

    print("Total Recovered: {0:9,d}".format(country_data['recovered']))
    print("Active Cases   : {0:9,d}".format(country_data['active']))

    print("\n\n")

def get_int(str):
    s = str.strip()
    return int(s.replace(',','').replace('+','')) if s else 0

country_name=raw_input("Enter the Country name: ")
covid19(country_name)