Python 爬虫+tkinter界面 实现历史天气查询
时间:2022-07-25
本文章向大家介绍Python 爬虫+tkinter界面 实现历史天气查询,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
文章目录
一、实现效果
1. python代码
import requests
from lxml import etree
import re
import tkinter as tk
from PIL import Image, ImageTk
from xpinyin import Pinyin
def get_image(file_nam, width, height):
im = Image.open(file_nam).resize((width, height))
return ImageTk.PhotoImage(im)
def spider():
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24',
"referer": "https://lishi.tianqi.com/chengdu/index.html"
}
p = Pinyin()
place = ''.join(p.get_pinyin(b1.get()).split('-')) # 获取地区文本框的输入 变为拼音
# 处理用户输入的时间
# 规定三种格式都可以 2018/10/1 2018年10月1日 2018-10-1
date = b2.get() # 获取时间文本框的输入
if '/' in date:
tm_list = date.split('/')
elif '-' in date:
tm_list = date.split('-')
else:
tm_list = re.findall(r'd+', date)
if int(tm_list[1]) < 10: # 1-9月 前面加 0
tm_list[1] = f'0{tm_list[1]}'
# 分析网页规律 构造url
# 直接访问有该月所有天气信息的页面 提高查询效率
url = f"https://lishi.tianqi.com/{place}/{''.join(tm_list[:2])}.html"
resp = requests.get(url, headers=headers)
html = etree.HTML(resp.text)
# xpath定位提取该日天气信息
info = html.xpath(f'//ul[@class="thrui"]/li[{int(tm_list[2])}]/div/text()')
# 输出信息格式化一下
info1 = ['日期:', '最高气温:', '最低气温:', '天气:', '风向:']
datas = [i + j for i, j in zip(info1, info)]
info = 'n'.join(datas)
t.insert('insert', ' 查询结果如下 nn')
t.insert('insert', info)
print(info)
win = tk.Tk()
win.title('全国各地历史天气查询系统')
win.geometry('500x500')
# 画布 设置背景图片
canvas = tk.Canvas(win, height=500, width=500)
im_root = get_image('test.jpg', width=500, height=500)
canvas.create_image(250, 250, image=im_root)
canvas.pack()
# 单行文本
L1 = tk.Label(win, bg='yellow', text="地区:", font=("SimHei", 12))
L2 = tk.Label(win, bg='yellow', text="时间:", font=("SimHei", 12))
L1.place(x=85, y=100)
L2.place(x=85, y=150)
# 单行文本框 可采集键盘输入
b1 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b2 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b1.place(x=140, y=100)
b2.place(x=140, y=150)
# 设置查询按钮
a = tk.Button(win, bg='red', text="查询", width=25, height=2, command=spider)
a.place(x=160, y=200)
# 设置多行文本框 宽 高 文本框中字体 选中文字时文字的颜色
t = tk.Text(win, width=30, height=8, font=("SimHei", 18), selectforeground='red') # 显示多行文本
t.place(x=70, y=280)
# 进入消息循环
win.mainloop()
2. 运行效果
运行效果如下:
二、基本思路
导入用到的库
import requests
from lxml import etree
import re
import tkinter as tk
from PIL import Image, ImageTk
from xpinyin import Pinyin
1. 爬虫部分
目标url:https://lishi.tianqi.com/
该网站提供了全国34个省、市所属的2290个地区的历史天气预报查询,数据来源于城市当天的天气信息,可以查询到历史天气气温,历史风向,历史风力等历史天气状况。
分析网页可以发现,某个地区、某个月的所有天气数据的url为:https://lishi.tianqi.com/ + 地区名字的拼音 + ‘/’ + 年月.html。
根据用户输入的地区和时间,进行字符串的处理,构造出url,用于request请求有该月所有天气信息的页面,获取响应后Xpath定位提取用户输入的要查询的日期的天气信息,查询结果显示在tkinter界面。
爬虫代码如下:
def spider():
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24',
"referer": "https://lishi.tianqi.com/chengdu/index.html"
}
p = Pinyin()
place = ''.join(p.get_pinyin(b1.get()).split('-')) # 获取地区文本框的输入 变为拼音
# 处理用户输入的时间
# 规定三种格式都可以 2018/10/1 2018年10月1日 2018-10-1
date = b2.get() # 获取时间文本框的输入
if '/' in date:
tm_list = date.split('/')
elif '-' in date:
tm_list = date.split('-')
else:
tm_list = re.findall(r'd+', date)
if int(tm_list[1]) < 10: # 1-9月 前面加 0
tm_list[1] = f'0{tm_list[1]}'
# 分析网页发现规律 构造url
# 直接访问有该月所有天气信息的页面 提高查询效率
url = f"https://lishi.tianqi.com/{place}/{''.join(tm_list[:2])}.html"
resp = requests.get(url, headers=headers)
html = etree.HTML(resp.text)
# xpath定位提取该日天气信息
info = html.xpath(f'//ul[@class="thrui"]/li[{int(tm_list[2])}]/div/text()')
# 输出信息格式化一下
info1 = ['日期:', '最高气温:', '最低气温:', '天气:', '风向:']
datas = [i + j for i, j in zip(info1, info)]
info = 'n'.join(datas)
t.insert('insert', ' 查询结果如下 nn')
t.insert('insert', info)
print(info)
2. tkinter界面
代码如下:
def get_image(file_nam, width, height):
im = Image.open(file_nam).resize((width, height))
return ImageTk.PhotoImage(im)
win = tk.Tk()
# 设置窗口title和大小
win.title('全国各地历史天气查询系统')
win.geometry('500x500')
# 画布 设置背景图片
canvas = tk.Canvas(win, height=500, width=500)
im_root = get_image('test.jpg', width=500, height=500)
canvas.create_image(250, 250, image=im_root)
canvas.pack()
# 单行文本
L1 = tk.Label(win, bg='yellow', text="地区:", font=("SimHei", 12))
L2 = tk.Label(win, bg='yellow', text="时间:", font=("SimHei", 12))
L1.place(x=85, y=100)
L2.place(x=85, y=150)
# 单行文本框 可采集键盘输入
b1 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b2 = tk.Entry(win, font=("SimHei", 12), show=None, width=35)
b1.place(x=140, y=100)
b2.place(x=140, y=150)
# 设置查询按钮 点击 调用爬虫函数实现查询
a = tk.Button(win, bg='red', text="查询", width=25, height=2, command=spider)
a.place(x=160, y=200)
# 设置多行文本框 宽 高 文本框中字体 选中文字时文字的颜色
t = tk.Text(win, width=30, height=8, font=("SimHei", 18), selectforeground='red') # 显示多行文本
t.place(x=70, y=280)
# 进入消息循环
win.mainloop()
tkinter界面效果如下:
作者:叶庭云 微信公众号:修炼Python CSDN:https://yetingyun.blog.csdn.net/ 本文仅用于交流学习,未经作者允许,禁止转载,更勿做其他用途,违者必究。 觉得文章对你有帮助、让你有所收获的话,期待你的点赞呀,不足之处,也可以在评论区多多指正。
- CTF中RSA题型解题思路及技巧
- 技术解析 | Web缓存欺骗测试
- SSH僵尸主机挖矿木马预警
- 看我如何通过Tor Onion在Windows中执行远程Shell
- 某租车系统JAVA代码审计
- 深入挖掘APP克隆实验
- Sickle:推荐一款优质ShellCode开发工具
- 看我教你如何修改QQ安装包实现绕过QQ语音红包验证来领红包
- “奇幻熊”(APT28)组织最新攻击
- GDB调试CVE-2018-5711 PHP-GD拒绝服务漏洞
- 高效与争议并存:大规模自动化渗透工具AutoSploit
- Android应用测试速查表
- ADB配置提权漏洞(CVE-2017-13212)原理与利用分析
- Fuzz自动化Bypass软WAF姿势
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- docker-compose 安装jenkins的正确姿势 实践笔记
- windows安装nginx注册为服务的正确姿势 并设置开机自启 实践笔记
- windows navicat连接oracle11G 自用 实践笔记
- docker安装官方redis集群并集群连接测试 的正确姿势 自用 实践笔记
- Asp.net Core 使用Jenkins + Dockor 实现持续集成、自动化部署(一):Jenkins安装
- Centos7安装轻量级TCP转发工具rinetd注册为服务的正确姿势 并设置开机自启 实践笔记 自用
- Connection open error . Connection Timeout Expired. The timeout period elapsed during the post-login
- macbook-12-2015款 安装win10系统 自用 实践笔记
- OpenGL ES 之attribute
- windows server 2012 r2 搭建文件服务器 问题记录 自用 实践笔记
- OpenGL ES 之uniform和varying
- OpenGL ES 绘制纹理
- Win10+Unlocker3+VMware15.5+MacOS10.14+xcode+QT for ios+虚拟机苹果系统 自用 实践笔记
- OpenGL ES 纹理过滤模式-glTexParameteri
- Jenkins时间修改为北京时间