Find current weather of any city using Open Weather Map API in Python (1)
Find current weather of any city using Open Weather Map API in Python (1)
The “Open Weather Map” is a service that provides weather data, including current weather data,
forecasts, and historical data to the developers of web services and mobile applications.
It provides an API with JSON, XML, and HTML endpoints and a limited free usage tier. Making
more than 60 calls per minute requires a paid subscription starting at USD 40 per month. Access to
historical data requires a subscription starting at 150 USD per month. Users can request current
weather information, extended forecasts, and graphical maps (showing cloud cover, wind speed,
pressure, and precipitation).
You can follow the “Weather Forecast Project” to create your own weather application using Weather
API using HTML, CSS and JavaScript.
❖ Current weather of any city using OpenWeatherMap API in Python
Modules Needed : -
• requests
• json
else:
print(" City Not Found ")
❖ Output :
❖ Second method :-
def weather(city):
city = city.replace(" ", "+")
res = requests.get(
f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.
6128j1j7&sourceid=chrome&ie=UTF-8', headers=headers)
print("Searching...\n")
soup = BeautifulSoup(res.text, 'html.parser')
location = soup.select('#wob_loc')[0].getText().strip()
time = soup.select('#wob_dts')[0].getText().strip()
info = soup.select('#wob_dc')[0].getText().strip()
weather = soup.select('#wob_tm')[0].getText().strip()
print(location)
print(time)
print(info)
print(weather+"°C")
❖ Sample Input:-
Mahoba
❖ Sample Output:-
Enter the Name of City -> Mahoba
Searching...
❖ Explanation:-
Here in the second approach, we will use some of the following modules and functions as listed
below,
• BeautifulSoup: It is a library in python used to extract data from HTML and XML files i.e.
for web scraping purposes. It generates a parse tree from the page source code, which can be
used to extract data in a more readable and hierarchical manner. For installing a beautiful
soup library in the system use the code below in the terminal,
pip install beautifulsoup
• Requests: Here we will use Python’s requests module to make HTTP requests. For installing
use the code below in the terminal.
• Here we are using headers because the headers contain protocol-specific information that is
placed before the raw message i.e retrieved from the website.
• After that, we will use the get() function and pass the google search in it along with the name
of the city to retrieve the data from google.
• Then we will use BeautifulSoup and parse the HTML data that is required from the website.
• Then we will use the select() function to retrieve the particular information like time, info,
location, store them in some variable, and, store them further.