Python 使用OpenWeatherMap API查找任何城市的当前天气
OpenWeatherMap确实是一项服务,为网络服务和移动应用程序的创建者提供天气信息,包括当前的天气信息、预测和历史数据。
它提供了一个有限的免费使用层,以及一个带有JSON、XML和HTML端点的API。用户可以要求扩展预报、图形地图和当前的天气信息(显示云量、风速、气压和降水)。
使用Python的OpenWeatherMap API,任何城市的当前天气
请求和json模块是必要的。
方法1:使用request模块和json
在这个方法中,我们将使用request和json模块。
# import the necessary components
import requests, json
# Entering of our API key here into it
api_key = "Entering of the API"
# base url variable for url storage
base_urlin = "http://api.openweathermap.org/data/2.5/weather?"
# Give in the city name into it
city_namein = input("Entering up the city name : ")
# complete_url to be variable to in the store
# complete url to be inserted for address
complete_urlin = base_urlin + "appidin=" + api_keyin + "&q=" + city_namein
# return response object for the get function of requests module
response = requests.get(complete_urlin)
# Change json form data into
# python format data using the json method
#of the response object.
x = response.json()
# Currently, x includes a list of nested dictionaries.
# A value of "cod" equal to "404"
#indicates that the city has been located;
#otherwise, the city has not been located.
if x["cod"] != "404":
# the "main" # key's value in the variable y
y = x["main"]
# Save the value that goes with the "temp" key of y.
current_temperaturein = y["temp"]
#Keep the value associated with the "pressure" key of y in memory. current_pressurein = y["pressure"]
# storing up the value corresponding
# to the y-"humidity" note's
current_humidityin = y["humidity"]
# the value of "weather" should be saved in the variable z.
z = x["weather"]
# storing up the value corresponding
#in the "description" key at the index 0 of z
weather_descriptionin = z[0]["description"]
# printing up the following values
print(" Temperature (in kelvin unit) = " +
str(current_temperaturein) +
"\n atmospheric pressure display(in hPa unit) = " +
str(current_pressurein) +
"\n humidity display(in percentage) = " + str(current_humidityin) +
"\n description = " + str(weather_descriptionin))
else:
print(" City Unknown ")
输出
Enter city name : Mumbai
Temperature display(in kelvin unit) = 318.15
atmospheric pressure display(in hPa unit) = 956
humidity display(in percentage) = 45
description = Cloudy
方法2:使用request模块和BeautifulSoup
在这个方法中,我们将使用 request 和 BeautifulSoup 模块。
#importing needed files
from bs4 import BeautifulSoup
#importing requests
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win32; x32) AppleWebKit/537.36 (KHTML, like Gecko) Brave/58.0.3029.110 Safari/537.3'}
def weather(place):
place = place.replace(" ", "+")
res = requests.get(
f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.36t89l2j0l4j89d5s660.6128j1j7&sourceid=chrome&ie=UTF-8', headers=headers)
print("Searching for..\n")
s = BeautifulSoup(res.text, 'html.parser')
l = s.select('#wob_loc')[0].getText().strip()
t =s.select('#wob_dts')[0].getText().strip()
i= s.select('#wob_dc')[0].getText().strip()
w = s.select('#wob_tm')[0].getText().strip()
print(l)
print(t)
print(i)
print(w+"°C")
place = input("Enter up the Name of City: ")
place = place+" w"
w (place)
print("Have a good Day:)")
输入
Hyderabad
输出
Enter the Name of City: Hyderabad
Searching for...
Hyderabad, Telangana
Wednesday, 10:00 pm
Partly Cloudy
28°C
Have a Good Day:)
解释一下
在这里,我们将采用下面第二个策略中描述的一些模块和功能。
BeautifulSoup。它是一个用于网络搜刮的Python包,允许用户从HTML和XML文件中检索数据。从页面的源代码中,它创建了一个解析树,可以用来以一种更容易理解和分层的方式检索信息。使用下面的终端代码来安装该系统与可爱的汤库。
请求
在这种情况下,为了进行HTTP请求,我们将使用Python中的request模块。在终端使用下面的代码进行安装。
在这种情况下,我们利用头文件,因为它们包含了协议特定的数据,这些数据在原始信息之前,是从网站上收集的信息。
然后,为了接收来自谷歌的数据,我们将采用get()方法并向其提供谷歌搜索和城市名称。然后,来自网页的必要的HTML数据将使用BeautifulSoup进行解析。
然后,在将它们存储在一个变量中后,我们将使用select()方法来检索特定的数据,如时间、信息和位置。