也是之前的公司需求,放上来记录一下。
import pandas as pd import requests import json AK = "*******" #你自己注册获取的key def getWeather(place): url = f"https://restapi.amap.com/v3/weather/weatherInfo?city={place}&extensions=base&key={AK}" # 高德地图extension=all可以查询预报天气 res = requests.get(url) json_data = json.loads(res.text) if json_data["status"] == "1": #这里有个坑,注意1是string return int(json_data["lives"][0]["temperature"]), int(json_data["lives"][0]["humidity"]), json_data["lives"][0]["reporttime"] #实况天气每小时更新多次,预报天气每天更新3次,分别在8、11、18点左右更新。还有风速等数据,根据自己需要提取 else: return "no data", json_data["info"], json_data["infocode"] if __name__ == "__main__": data = pd.read_excel("place.xlsx") result = [] for i in range(0,len(data)): place = data.iloc[i,0] temperature, humidity, time = getWeather(place) result.append([place, temperature, humidity, time]) pd.DataFrame(result).to_excel( "result.xlsx", header=["地点", "温度", "湿度", "更新时间"], encoding="utf-8" )