👩‍💻 🌦Get weather information for a specified city using Python

mahabub.devs3
Mahabubur Rahman
Published on Oct, 23 2024 1 min read 0 comments
image

Installation 

Install bellow package

pip install beautifulsoup4

pip install requests

 

Usages 

Write bellow code 

import requests
from bs4 import BeautifulSoup

city = input("Enter City Name: ")
city_formatted = city.lower().replace(" ", "-")
url = f"https://www.timeanddate.com/weather/usa/{city_formatted}"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
try:
    temperature = soup.find("div", class_="h2").get_text(strip=True)
    description = soup.find("div", class_="h2").find_next("p").get_text(strip=True)
    print(f"Weather in {city}:")
    print(f"Temperature: {temperature}")
    print(f"Condition: {description}")
except AttributeError:
    print("Please check the city name and try again.")

 

 

Enter City Name: Geneva
Weather in Geneva:
Temperature: 16 °C
Condition: Clear.

 

 

Enter City Name: New York
Weather in New York:
Temperature: 17 °C
Condition: Clear.

 

0 Comments