Chintan Donda
Convert temperature from Ferenheit to Celcius
2b3239a
import requests
from bs4 import BeautifulSoup as bs
import src.constants as constants_utils
import logging
logging.basicConfig(
format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
level=logging.INFO,
datefmt="%Y-%m-%d %H:%M:%S"
)
logger = logging.getLogger(__name__)
class WEATHER:
def __init__(self):
self.base_url = 'https://nwp.imd.gov.in/blf/blf_temp'
self.headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
}
self.state_names_codes = {}
self.districts = []
def get_state_names_codes(
self
):
response = requests.get(
self.base_url,
headers=self.headers,
)
soup = bs(response.text, 'html.parser')
for option in soup.find_all('option'):
if option.text.strip() == 'Select':
continue
self.state_names_codes[option.text.strip()] = str(option['value'].split('=')[-1][:2])
return self.state_names_codes
def get_district_names(
self,
state_name
):
url = f"{self.base_url}/dis.php?value={constants_utils.WEATHER_FORECAST_STATE_CODES.get(state_name, '') + state_name}"
response = requests.get(
url,
headers=self.headers,
)
soup = bs(response.text, 'html.parser')
self.districts = soup.findAll('select', {'name': 'dis'}, limit=None)
self.districts = [district.strip() for district in self.districts[0].text.split('\n') if district and district != 'Select']
return self.districts
# Weather forecast from Govt. website
def get_weather_forecast(
self,
state,
district,
is_block_level=False
):
self.district_url = f"{self.base_url}/block.php?dis={constants_utils.WEATHER_FORECAST_STATE_CODES.get(state, '') + district}"
self.block_url = f'{self.base_url}/table2.php'
response = requests.get(self.district_url if not is_block_level else self.block_url)
soup = bs(response.text, 'html.parser')
scripts = soup.findAll('font')[0]
return scripts.text
# Weather using Google weather API
def get_weather(
self,
city
):
city = city + " weather"
city = city.replace(" ", "+")
soup = bs(
requests.get(f"https://www.google.com/search?q=weather+{city}").content,
'html.parser'
)
temperature = soup.find('div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text.strip()
time = soup.find('div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text.split('\n')[0].strip()
time = ' '.join(time.split())
info = soup.find('div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text.split('\n')[1].strip()
# Convert temperature from Ferenheit to Celcius
if '°F' in temperature:
temp = temperature.split('°')[0]
if temp:
try:
temp = int(temp)
celcius = int((temp - 32) * (5/9))
temperature = str(celcius) + '°C'
except Exception as e:
logger.error(f'Cannot convert temperature from Ferenheit to Celcius!')
pass
return time, info, temperature