因此,我有一个主意,要从一个朋友那里发出天气指令,我今天就开始做这个工作。安装了软件包,设置了代码等等。下面是我的天气API代码的代码,我想把它放到一个命令中。(!天气)。在DPY公会的人推荐了aiohttp,这看起来太困难了,因为我是一个新的程序员。有人可以用勺子喂我吗?API代码如下:
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
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")
city = input("Enter the Name of City -> ")
city = city+" weather"
weather(city)
print("Have a Nice Day:)")
# This code is contributed by adityatri发布于 2022-04-13 18:19:00
从weathermap网站获取API密钥。这是一个例子,说明这可能是什么样子。很容易翻译成命令。
如果您想让它具有自己的功能,只需使用以下代码即可。将返回的是一个元组。
list_weather = weatherFrog()
print(list_weather[0]) 0是温度,1是湿度,2是描述。
代码:
def weatherFrog(city):
api_key = YOUR_API_KEY
base_url = "https://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + api_key + "&q=" + city
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_humidiy = str(y["humidity"]) + "%"
z = x["weather"]
current_temperaturetwo = str(round(current_temperature - 273.15, 2)) + " Degrees Celsius"
en_weather_description = z[0]["description"]
return current_temperaturetwo, current_humidiy, en_weather_descriptionhttps://stackoverflow.com/questions/71833881
复制相似问题