python项目之 天气 优化版
抓取的数据源
使用的类库
thinter
requests
beautifulsoup
思路
抓取到返回的数据,解析后,存到本地和显示在GUI界面上。
更新的地方
全部封装为函数
界面如下
源码奉上
#encoding = 'utf8'
#########################
##coding by 刘云飞
#########################
import requests
from bs4 import BeautifulSoup
from tkinter import *
import datetime
data = {}
URL_short = 'http://wthrcdn.etouch.cn/WeatherApi?citykey='
def city(city = 'shanghai'):
if(city == 'shanghai'):
urls = URL_short+'101020100'
if(city == 'beijin'):
urls = URL_short+'101010100'
return urls
def refresh():
pass
def get_data():
requests.session()
r = requests.get(city())
#print(r.status_code)
soup = BeautifulSoup(r.text,'lxml')
#print(soup.prettify())
a = soup.find_all('city')
data['city'] = a[0].get_text()
a = soup.find_all('wendu')
data['wendu'] = a[0].get_text()
a = soup.find_all('shidu')
data['shidu'] = a[0].get_text()
a = soup.find_all('fengli')
data['fengli'] = a[0].get_text()
a = soup.find_all('fengxiang')
data['fengxiang'] = a[0].get_text()
a = soup.find_all('quality')
data['quality'] = a[0].get_text()
a = soup.find_all('pm25')
data['pm25'] = a[0].get_text()
date_time = datetime.datetime.now().strftime('%Y_%m_%d')
filename = date_time +'.txt'
data['date_time'] = date_time
data['filename'] = filename
return data
def write_data(data):
with open(data['filename'],'w',encoding='utf8') as f:
f.write('城市:'+data['city'] +'\n')
f.write('温度:'+data['wendu'] +'\n')
f.write('湿度:'+data['shidu'] +'\n')
f.write('风力:'+ data['fengli'] +'\n')
f.write('风向:'+ data['fengxiang'] +'\n')
f.write('空气质量:'+data['quality'] +'\n')
f.write('PM2.5:'+data['pm25'] +'\n')
####下面是界面程序
def gui(data):
gui =Tk()
gui.title("天气查询 by 刘云飞")
gui.geometry('400x320')
l_da = Label(gui,text="日期:"+ data['date_time'],font = 'Helvetica -18')
l_da.pack(side = TOP)
l_chengshi = Label(gui,text = '城市:'+data['city'],font = 'Arial -18',width = 20,height =1)
l_chengshi.pack(side = TOP)
l_wendu = Label(gui,text = '温度:'+data['wendu'],font = 'Helvetica -18',width = 20,height =1)
l_wendu.pack(side = TOP)
l_shidu = Label(gui,text = '湿度:'+data['shidu'],font = 'Helvetica -18',width = 20,height =1)
l_shidu.pack(side = TOP)
l_fengx = Label(gui,text = '风向:'+data['fengxiang'],font = 'Helvetica -18',width = 20,height =1)
l_fengx.pack(side = TOP)
l_fengli= Label(gui,text = '风力:'+data['fengli'],font = 'Helvetica -18',width = 20,height =1)
l_fengli.pack(side = TOP)
l_qu = Label(gui,text = '空气质量:'+data['quality'],font = 'Helvetica -18',width = 20,height =1)
l_qu.pack(side = TOP)
l_pm = Label(gui,text = 'PM2.5:'+data['pm25'],font = 'Helvetica -18',width = 20,height =1)
l_pm.pack(side = TOP)
ref = Button(gui,text = "更新",font = 'Helvetica -18',command = refresh,activeforeground = 'white',\
activebackground = 'green')
ref.pack(side = TOP)
gui.mainloop()
def main():
get_data()
write_data(data)
gui(data)
pass
if __name__ == '__main__':
main()