weather.py

1import requests
2from bs4 import BeautifulSoup
3
4# Settings
5city = "Tokyo"
6units = "imperial"  # Unit system {imperial or metric}
7
8
9def convert_units(temp, units):
10        return f"{temp:.1f}°F"
11    
12def normalize_condition(condition):
13    # Take something like "cloudy" and return "Cloudy"
14    return condition.capitalize()
15
16def get_weather():
17    try:
18        url = f"https://www.google.com/search?q=weather+{city}"
19        response = requests.get(url)
20        soup = BeautifulSoup(response.text, "html.parser")
21        
22        # Extract temperature
23        temp = soup.find("div", class_="BNeawe iBp4i AP7Wnd").text
24        temp = float(temp.split("°")[0])
25        
26        # Extract weather condition
27        condition = soup.find("div", class_="BNeawe tAd8D AP7Wnd").text.split("\n")[1].lower().replace(" ", "_")
28        condition = normalize_condition(condition)
29        return f"{convert_units(temp, units)} ({condition})"
30    except Exception as e:
31        return ""  # Return empty string if there's an error
32
33def main():
34    weather_info = get_weather()
35    return weather_info
36
37if __name__ == "__main__":
38    print(main())
39
40