利用 Python+Excel 制作天氣預報表!
今天給大家介紹一個Python+Excel的實戰(zhàn)項目,非常有趣。
主要使用xlwings和requests這兩個Python庫,以及Office的Excel。
xlwings處理表格,requests則是請求數據。
先從Excel中獲取城市信息,然后請求接口,獲取到天氣信息,再返回給Excel。
具體操作可以看下圖~

在城市欄輸入杭州,點擊查詢按鈕,表格的數據就會發(fā)生變化,的確是杭州的天氣預報。
① 數據獲取
既然是天氣預報,那肯定是需要天氣數據的。
找了一圈國內開放的天氣API接口,大多都是需要注冊,小F果斷放棄。
騰訊倒是有個不錯的,可惜接口信息不太完整,沒有相應的數據說明。
地址:https://tianqi.qq.com/
接口地址:https://wis.qq.com/weather/common

最終選擇了一個國外的天氣API接口。
地址:https://www.metaweather.com/zh/

并沒有提供國內所有的城市,目前只有10個城市。
所以要想城市多一些,騰訊的天氣接口還是可以考慮的。
一共是有10種天氣狀態(tài),并且提供了相關的天氣狀態(tài)圖片,可以供我們使用。
圖片已經下載下來了,需要的小伙伴可以文末獲取哦!

首先通過查詢,獲取城市的ID值。

然后根據ID值,再去獲取對應的天氣信息。

相關名稱的中英文對照如下。
# 天氣--中英文名對照
weather = {
'Snow': '雪',
'Sleet': '雨夾雪',
'Hail': '冰雹',
'Thunderstorm': '雷陣雨',
'Heavy Rain': '大雨',
'Light Rain': '小雨',
'Showers': '陣雨',
'Heavy Cloud': '陰',
'Light Cloud': '多云',
'Clear': '晴'
}
# 城市--中英文名對照
citys = {
'北京': 'Beijing',
'成都': 'Chengdu',
'東莞': 'Dongguan',
'廣州': 'Guangzhou',
'杭州': 'Hangzhou',
'香港': 'Hong Kong',
'上海': 'Shanghai',
'深圳': 'Shenzhen',
'天津': 'Tianjin',
'武漢': 'Wuhan'
}
② 創(chuàng)建表格
安裝xlwings庫,并且使用命令行創(chuàng)建項目。
# 安裝xlwings
pip install xlwings -i https://mirror.baidu.com/pypi/simple/
# 命令行運行
xlwings quickstart weatherapp --standalone
如此便會生成兩個文件,Python和Excel文件。

其中weatherapp.py的文件內容如下。
import xlwings as xw
def main():
wb = xw.Book.caller()
sheet = wb.sheets[0]
if sheet["A1"].value == "Hello xlwings!":
sheet["A1"].value = "Bye xlwings!"
else:
sheet["A1"].value = "Hello xlwings!"
if __name__ == "__main__":
xw.Book("weatherapp.xlsm").set_mock_caller()
main()
而Excel是什么內容也沒有的,打開時會提示是否啟用宏,選擇是。
然后需要將Excel的開發(fā)工具打開,后面會使用它插入一些元素。

上圖為Mac電腦的設置,Windows電腦設置起來也很簡單,具體可以百度。
通過點擊開發(fā)工具選項,我們可以使用Excle的Visual Basic 編輯器(VBA),還能插入按鈕(查詢按鈕)。

然后我在表格中插入一個點擊按鈕。

選擇宏名稱為SampleCall,宏的位置為當前工作簿。

點擊按鈕1,A1單元格出現(xiàn)內容Hello xlwings!。

再次點擊,A1單元格內容變?yōu)锽ye xlwings!。

也就意味著,修改weatherapp.py文件的代碼,即可實現(xiàn)Excel的交互操作。
下面對表格進行頁面設計,畢竟要讓表格好看起來。

設置表格的行高、列寬、背景色、固定文字內容等信息。
將單元格C3名稱設置為city_name,插入6張?zhí)枅D片,排列在單元格C9~H9處,居中對齊,圖片也改名為no.1~no.6。
修改weatherapp.py文件代碼如下。
import json
from pathlib import Path
import requests
import xlwings as xw
# 天氣--中英文名對照
weather = {
'Snow': '雪',
'Sleet': '雨夾雪',
'Hail': '冰雹',
'Thunderstorm': '雷陣雨',
'Heavy Rain': '大雨',
'Light Rain': '小雨',
'Showers': '陣雨',
'Heavy Cloud': '陰',
'Light Cloud': '多云',
'Clear': '晴'
}
# 城市--中英文名對照
citys = {
'北京': 'Beijing',
'成都': 'Chengdu',
'東莞': 'Dongguan',
'廣州': 'Guangzhou',
'杭州': 'Hangzhou',
'香港': 'Hong Kong',
'上海': 'Shanghai',
'深圳': 'Shenzhen',
'天津': 'Tianjin',
'武漢': 'Wuhan'
}
def main():
# 通過runpython從excel中調用python函數
wb = xw.Book.caller()
sht = wb.sheets[0]
# 從Excel中讀取城市信息
city_name = citys[sht.range("city_name").value]
# 獲取城市的ID值, 即woeid
URL_CITY = f"https://www.metaweather.com/api/location/search/?query={city_name}"
response_city = requests.request("GET", URL_CITY)
city_title = json.loads(response_city.text)[0]["title"]
city_id = json.loads(response_city.text)[0]["woeid"]
# 獲取城市的天氣信息
URL_WEATHER = f"https://www.metaweather.com/api/location/{city_id}/"
response_weather = requests.request("GET", URL_WEATHER)
weather_data = json.loads(response_weather.text)["consolidated_weather"]
# 創(chuàng)建空列表, 存儲數據
min_temp = []
max_temp = []
weather_state_name = []
weather_state_abbr = []
applicable_date = []
# 處理數據
for index, day in enumerate(weather_data):
# 最低溫度
min_temp.append(weather_data[index]["min_temp"])
# 最高溫度
max_temp.append(weather_data[index]["max_temp"])
# 天氣情況
weather_state_name.append(weather[weather_data[index]["weather_state_name"]])
# 天氣情況縮寫
weather_state_abbr.append(weather_data[index]["weather_state_abbr"])
# 日期
applicable_date.append(weather_data[index]["applicable_date"])
# 將獲取到的值填充到Excel中
sht.range("C5").value = applicable_date
sht.range("C6").value = weather_state_name
sht.range("C7").value = max_temp
sht.range("C8").value = min_temp
sht.range("D3").value = city_title
# 創(chuàng)建列表
icon_names = ["no.1", "no.2", "no.3", "no.4", "no.5", "no.6"]
# 設置天氣圖片路徑
icon_path = Path(__file__).parent / "images"
# 將天氣情況與天氣圖片進行匹配,更新表格
for icon, abbr in zip(icon_names, weather_state_abbr):
image_path = Path(icon_path, abbr + ".png")
sht.pictures.add(image_path, name=icon, update=True)
if __name__ == "__main__":
# 設置用于調試caller()的excel文件,可以直接在python里運行
xw.Book("weatherapp.xlsm").set_mock_caller()
main()
此時我們打開Excel表格,在城市欄輸入10個城市中的一個,然后點擊查詢按鈕,天氣就會更新。

接下來幾天,廣州都是大暴雨,廣州的小伙伴可要注意了~
好了,本期的分享就到此結束了,有興趣的小伙伴可以自行去實踐學習。
本次使用到的代碼和數據。鏈接:
https://pan.baidu.com/s/12Dg034Uo9n8EWXmciqijlQ 密碼:oh4t





