变幻气象站

变幻气象站

Python 爬虫+tkinter界面 实现历史天气查询

admin 199 2
文章目录

一、实现效果1.python代码2.运行效果二、基本思路1.爬虫部分2.tkinter界面

一、实现效果

1.python代码

importrequestsfromlxmlimportetreeimportreimporttkinterastkfromPILimportImage,ImageTkfromxpinyinimportPinyindefget_image(file_nam,width,height):im=(file_nam).resize((width,height))(im)defspider():headers={'user-agent':'Mozilla/5.0(;WOW64)AppleWebKit/535.24(KHTML,likeGecko)Chrome/19.0.1055.1Safari/535.24',"referer":""}p=Pinyin()place=''.join(_pinyin(()).split('-'))处理用户输入的时间获取时间文本框的输入if'/'indate:tm_list=('/')elif'-'indate:tm_list=('-')else:tm_list=(r'\d+',date)ifint(tm_list[1])10:分析网页规律构造urlxpath定位提取该日天气信息info=(f'//ul[@class="thrui"]/li[{int(tm_list[2])}]/div/text()')画布设置背景图片canvas=(win,height=500,width=500)im_root=get_image('',width=500,height=500)_image(250,250,image=im_root)()单行文本框可采集键盘输入b1=(win,font=("SimHei",12),show=None,width=35)b2=(win,font=("SimHei",12),show=None,width=35)(x=140,y=100)(x=140,y=150)设置多行文本框宽高文本框中字体选中文字时文字的颜色t=(win,width=30,height=8,font=("SimHei",18),selectforeground='red')进入消息循环()


2.运行效果

运行效果如下:



二、基本思路

导入用到的库

importrequestsfromlxmlimportetreeimportreimporttkinterastkfromPILimportImage,ImageTkfromxpinyinimportPinyin

1.爬虫部分

目标url:

分析网页可以发现,某个地区、某个月的所有天气数据的url为:‘/’+年月.html。
根据用户输入的地区和时间,进行字符串的处理,构造出url,用于request请求有该月所有天气信息的页面,获取响应后Xpath定位提取用户输入的要查询的日期的天气信息,查询结果显示在tkinter界面。

爬虫代码如下:

tkinter界面效果如下: