python天气查询_Python学习笔记——天气查询代码
天气查询代码1
# 此程序无法运行,因为中国天气网的api接口被关闭了
import urllib.request
import json
import pickle
#建立城市字典
pickle_file = open(r'F:\codes\python\python\fishc\file\city_date.pkl', 'rb')
city = pickle.load(pickle_file)
password = input('请输入城市:')
name1 = city[password]
# header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'}
# req = urllib.request.Request(url='http://m.weather.com.cn/data/'+name1+'.html',data=None,headers=headers)
# # 接着把File那句改成
# File1 = urllib.request.urlopen(req)
File1 = urllib.request.urlopen('http://m.weather.com.cn/data/'+ name1 +'.html')#打开url
weatherHTML = File1.read().decode('utf-8')#读入打开的url
weatherJSON = json.JSONDecoder().decode(weatherHTML)#创建json
weatherInfo = weatherJSON['weatherinfo']
#打印信息
print ( '城市:', weatherInfo['city'])
print ('时间:', weatherInfo['date_y'])
print ( '24小时天气:')
print ('温度:', weatherInfo['temp1'])
print ('天气:', weatherInfo['weather1'])
print ('风速:', weatherInfo['wind1'])
print ('紫外线:', weatherInfo['index_uv'])
print ('穿衣指数:', weatherInfo['index_d'])
print ('48小时天气:')
print ('温度:', weatherInfo['temp2'])
print ('天气:', weatherInfo['weather2'])
print ('风速:', weatherInfo['wind2'])
print ('紫外线:', weatherInfo['index48_uv'])
print ('穿衣指数:', weatherInfo['index48_d'])
print ('72小时天气:')
print ('温度:', weatherInfo['temp3'])
print ('天气:', weatherInfo['weather3'])
print ('风速:', weatherInfo['wind3'])
input ('按任意键退出:')
请输入城市:南丰
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
in ()
18 # File1 = urllib.request.urlopen(req)
19
---> 20 File1 = urllib.request.urlopen('http://m.weather.com.cn/data/'+ name1 +'.html')#打开url
21 weatherHTML = File1.read().decode('utf-8')#读入打开的url
22 weatherJSON = json.JSONDecoder().decode(weatherHTML)#创建json
F:\tools\Anaconda\anaconda\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
221 else:
222 opener = _opener
--> 223 return opener.open(url, data, timeout)
224
225 def install_opener(opener):
F:\tools\Anaconda\anaconda\lib\urllib\request.py in open(self, fullurl, data, timeout)
530 for processor in self.process_response.get(protocol, []):
531 meth = getattr(processor, meth_name)
--> 532 response = meth(req, response)
533
534 return response
F:\tools\Anaconda\anaconda\lib\urllib\request.py in http_response(self, request, response)
640 if not (200 <= code < 300):
641 response = self.parent.error(
--> 642 'http', request, response, code, msg, hdrs)
643
644 return response
F:\tools\Anaconda\anaconda\lib\urllib\request.py in error(self, proto, *args)
568 if http_err:
569 args = (dict, 'default', 'http_error_default') + orig_args
--> 570 return self._call_chain(*args)
571
572 # XXX probably also want an abstract factory that knows when it makes
F:\tools\Anaconda\anaconda\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
502 for handler in handlers:
503 func = getattr(handler, meth_name)
--> 504 result = func(*args)
505 if result is not None:
506 return result
F:\tools\Anaconda\anaconda\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
648 class HTTPDefaultErrorHandler(BaseHandler):
649 def http_error_default(self, req, fp, code, msg, hdrs):
--> 650 raise HTTPError(req.full_url, code, msg, hdrs, fp)
651
652 class HTTPRedirectHandler(BaseHandler):
HTTPError: HTTP Error 403: Forbidden
天气查询代码2
import urllib.request
import gzip
import json
print('------天气查询------')
def get_weather_data() :
city_name = input('请输入要查询的城市名称:')
url1 = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(city_name)
url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
#网址1只需要输入城市名,网址2需要输入城市代码
#print(urllib.parse.quote(city_name))
weather_data = urllib.request.urlopen(url1).read()
#读取网页数据
weather_data = gzip.decompress(weather_data).decode('utf-8')
#解压网页数据
weather_dict = json.loads(weather_data)
#将json数据转换为dict数据
return weather_dict
def show_weather(weather_data):
weather_dict = weather_data
#将json数据转换为dict数据
if weather_dict.get('desc') == 'invilad-citykey':
print('你输入的城市名有误,或者天气中心未收录你所在城市')
elif weather_dict.get('desc') =='OK':
forecast = weather_dict.get('data').get('forecast')
print('城市:',weather_dict.get('data').get('city'))
print('温度:',weather_dict.get('data').get('wendu')+'℃ ')
print('感冒:',weather_dict.get('data').get('ganmao'))
print('风向:',forecast[0].get('fengxiang'))
print('风级:',forecast[0].get('fengli'))
print('高温:',forecast[0].get('high'))
print('低温:',forecast[0].get('low'))
print('天气:',forecast[0].get('type'))
print('日期:',forecast[0].get('date'))
print('*******************************')
four_day_forecast =input('是否要显示未来四天天气,是/否:')
if four_day_forecast == '是' or four_day_forecast == 'Y' or four_day_forecast == 'y':
for i in range(1,5):
print('日期:',forecast[i].get('date'))
print('风向:',forecast[i].get('fengxiang'))
print('风级:',forecast[i].get('fengli'))
print('高温:',forecast[i].get('high'))
print('低温:',forecast[i].get('low'))
print('天气:',forecast[i].get('type'))
print('--------------------------')
print('***********************************')
show_weather(get_weather_data())
------天气查询------
请输入要查询的城市名称:南丰
%E5%8D%97%E4%B8%B0
城市: 南丰
温度: 25℃
感冒: 各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。
风向: 南风
风级:
高温: 高温 28℃
低温: 低温 16℃
天气: 晴
日期: 17日星期三
*******************************
是否要显示未来四天天气,是/否:n
***********************************
天气查询代码3
import urllib.request
import gzip
import json
print('------021王掌柜 天气查询------')
def get_weather_data():
city_name = input('请输入要查询的城市名称:')
url1 = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib.parse.quote(city_name)
url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
#网址1只需要输入城市名,网址2需要输入城市代码
#print(url1)
weather_data = urllib.request.urlopen(url1).read()
#读取网页数据
weather_data = gzip.decompress(weather_data).decode('utf-8')
#解压网页数据
weather_dict = json.loads(weather_data)
#将json数据转换为dict数据
return weather_dict
def show_weather(weather_data):
weather_dict = weather_data
#将json数据转换为dict数据
if weather_dict.get('desc') == 'invilad-citykey':
print('你输入的城市名有误,或者天气中心未收录你所在城市')
elif weather_dict.get('desc') =='OK':
forecast = weather_dict.get('data').get('forecast')
print('城市:',weather_dict.get('data').get('city'))
print('温度:',weather_dict.get('data').get('wendu')+'℃ ')
print('感冒:',weather_dict.get('data').get('ganmao'))
print('风向:',forecast[0].get('fengxiang'))
print('风级:',forecast[0].get('fengli'))
print('高温:',forecast[0].get('high'))
print('低温:',forecast[0].get('low'))
print('天气:',forecast[0].get('type'))
print('日期:',forecast[0].get('date'))
print('*******************************')
four_day_forecast =input('是否要显示未来四天天气,是/否:')
if four_day_forecast == '是' or four_day_forecast =='y':
for i in range(1,5):
print('日期:',forecast[i].get('date'))
print('风向:',forecast[i].get('fengxiang'))
print('风级:',forecast[i].get('fengli'))
print('高温:',forecast[i].get('high'))
print('低温:',forecast[i].get('low'))
print('天气:',forecast[i].get('type'))
print('--------------------------')
print('***********************************')
show_weather(get_weather_data())
b = 'yes'
b = input('查询继续,输入 NO 退出程序:')
while (b!= 'no') and (b!='NO'):
show_weather(get_weather_data())
------021王掌柜 天气查询------
请输入要查询的城市名称:南丰
城市: 南丰
温度: 25℃
感冒: 各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。
风向: 南风
风级:
高温: 高温 28℃
低温: 低温 16℃
天气: 晴
日期: 17日星期三
*******************************
是否要显示未来四天天气,是/否:否
***********************************
查询继续,输入 NO 退出程序:no
天气查询代码4
# 由于未安装easygui模块,所以这里也暂时不能运行
import urllib.request
import gzip
import json
import easygui as g
g.msgbox("------天气查询------")
def get_weather_data() :
msg = "请输入要查询的城市名称:"
title = "天气查询器"
city_name = g.enterbox(msg, title)
#city_name = input('请输入要查询的城市名称:')
url1 = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib.parse.quote(city_name)
url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
#网址1只需要输入城市名,网址2需要输入城市代码
#print(url1)
weather_data = urllib.request.urlopen(url1).read()
#读取网页数据
weather_data = gzip.decompress(weather_data).decode('utf-8')
#解压网页数据
weather_dict = json.loads(weather_data)
#将json数据转换为dict数据
return weather_dict
def query_weather(weather_dict):
weather_dict.get('desc') =='OK'
forecast = weather_dict.get('data').get('forecast')
msg = "查询天气信息如下"
title = "查询结果"
text = "城市:"+weather_dict.get('data').get('city')+\
"\n"+"温度:"+ weather_dict.get('data').get('wendu')+'℃ '+\
"\n"+"感冒:"+ weather_dict.get('data').get('ganmao')+\
"\n"+"风向:"+ forecast[0].get('fengxiang')+\
"\n"+"风级:"+ forecast[0].get('fengli')+\
"\n"+"高温:"+ forecast[0].get('high')+\
"\n"+"低温:"+ forecast[0].get('low')+\
"\n"+"天气:"+ forecast[0].get('type')+\
"\n"+"日期:"+ forecast[0].get('date')
g.textbox(msg,title,text)
msg = "是否要显示未来四天天气,是/否:"
title = "未来天气"
four_day_forecast = g.enterbox(msg, title)
if four_day_forecast == '是':
text = ''
for i in range(1,5):
msg = "查询天气信息如下"
title = "查询结果"
text += '日期:'+forecast[i].get('date')+\
"\n"+'风向:'+forecast[i].get('fengxiang')+\
"\n"+'风级:'+forecast[i].get('fengli')+\
"\n"+'高温:'+forecast[i].get('high')+\
"\n"+'低温:'+forecast[i].get('low')+\
"\n"+'天气:'+forecast[i].get('type')+\
"\n"+'******************************'+"\n"
g.textbox(msg,title,text)
elif four_day_forecast == '否':
g.msgbox('您请求不查询未来四天天气')
else:
g.msgbox('您输入的信息有误')
def show_weather(weather_data):
weather_dict = weather_data
#将json数据转换为dict数据
if weather_dict.get('desc') == 'invilad-citykey':
g.msgbox("你输入的城市名有误,或者天气中心未收录你所在城市")
weather_dict = get_weather_data()
query_weather(weather_dict)
else:
query_weather(weather_dict)
show_weather(get_weather_data())
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
in ()
2 import gzip
3 import json
----> 4 import easygui as g
5
6 g.msgbox("------天气查询------")
ModuleNotFoundError: No module named 'easygui'
python天气查询_Python学习笔记——天气查询代码相关推荐
- python tkinter 表格_python学习笔记(Tkinter编程利用Treeview实现表格自动更新)
博主今天总结这段时间抽空写的一个GUI编程项目 功能是查看本地打印机队列,可选择指定队列重新打印 直接上图 UI设计包括3个区域左上方,右上方和下方列表区域 使用网格grid方法来分配位置 下面是界面 ...
- python pow和**_Python学习笔记 | 实例3:天天向上的力量
本文为中国大学MOOC<Python语言程序设计>课程学习笔记,课程主讲:嵩天老师,练习平台:Python123,参考教材:<Python语言程序设计基础> 天天向上的力量 加 ...
- python eval 入门_Python学习笔记整理3之输入输出、python eval函数
Python学习笔记整理3之输入输出.python eval函数 来源:中文源码网 浏览: 次 日期:2018年9月2日 Python学习笔记整理3之输入输出.python eval函数 ...
- python分组求和_Python学习笔记之pandas索引列、过滤、分组、求和功能示例
本文实例讲述了Python学习笔记之pandas索引列.过滤.分组.求和功能.分享给大家供大家参考,具体如下: 前面我们已经把519961(基金编码)这种基金的历史净值明细表html内容抓取到了本地, ...
- python图形设置_python学习笔记——基本图形绘制
1.python蟒蛇python蟒蛇代码 #PythonDraw.py import turtle turtle.setup(650,350,200,200)# 设置画布的长.宽.起点 turtle. ...
- python dict遍历_Python学习笔记:19个pythonic编程习惯,让你的Python入门更优雅
Python最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净.整洁.一目了然. 要写出 Pythonic(优雅的.地道的.整洁的)代码,需要多看多学大牛们写的代码,github 上有很多非常优 ...
- python通信信号处理_python学习笔记——信号模块signal(示例代码)
基于python学习笔记--多进程间通信--Linux信号基础的学习基础,进一步学习Python标准库中的signal模块. 尽管signal是python中的模块,但是主要针对UNIX平台(比如Li ...
- python编程计算器_Python学习笔记:用Python开发一个计算器项目
最近抽空看了下python的学习文档,发现开发工具以及资料支持对开发者相当的友好,相比之下,以前用TCL&Tk做的项目主要缺点有两个:1,开发难度大,调试手段只有靠print一种,而且语法错误 ...
- python url拼接_python学习笔记——urllib篇
1 request模块:用于打开和读取 URL. 使用urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None, capath=None ...
最新文章
- 奔图打印机显示未连接_手机连接奔图打印机,无法打印的解决方法
- appcontroller.php,php用什么开发app接口
- LeetCode-1.Two Sum
- jdbc在项目中的应用
- c# WINFORM SOCKET编程-简单聊天程序(服务端)
- 跨境电商Crazysales的高稳定性架构实践
- 【剑指offer】21、调整数组顺序使奇数在偶数前面
- CloudEra Hadoop VMWare单节点环境设置
- 浏览器是否支持Html5
- fpga电平约束有什么作用_FPGA开发全攻略——时序约束
- iMazing 2.11.7 WinMac 中文版 — iOS设备管理工具
- Linux——万字总结用户与组相关知识!建议收藏!
- java语言开发的万能简历解析,任何简历都可以 规范格式化数据保存入库! - CSDN博客
- python入门教程慕课网_秒懂系列 | 史上最简单的Python Django入门教程
- 推荐1个视频播放画中画工具!
- [cstc2021]wp
- 4.Executor执行器
- Orcal数据库中ORA-01861: 文字与格式字符串不匹配
- 请问想考软考,零基础的话,哪个证书最好考呢
- uci数据集中的缺失数据_从uci早期糖尿病风险预测数据集中创建分类器
热门文章
- PSD分层模板素材|电商页面这样设计,转化率成倍提高!
- android版本怎么设置,安卓系统手机怎么用
- Madagascar编程的Makefile文件配置
- libevent的两个服务端、客户端示例(C语言)
- maven+springboot整合mybatis(十二)
- RecycleView添加HeaderView和FooterView
- python的decode函数报错_python2和python3的编码encode解码decode函数
- html页面锁屏,锁屏页面.html
- c语言学习-判断一个数的正、负,输出相应信息
- 【专栏精选】实战:使用LeanCloud实现玩家注册