天气查询代码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)

<ipython-input-1-43b6de524dbb> in <module>()
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℃
感冒: 各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。
风向: 南风
风级: <![CDATA[<3级]]>
高温: 高温 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℃
感冒: 各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。
风向: 南风
风级: <![CDATA[<3级]]>
高温: 高温 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)

<ipython-input-3-89f039e01c80> in <module>()
2 import gzip
3 import json
----> 4 import easygui as g
5
6 g.msgbox("------天气查询------") ModuleNotFoundError: No module named 'easygui'

Python学习笔记——天气查询代码的更多相关文章

  1. python 学习笔记 12 -- 写一个脚本获取城市天气信息

    近期在玩树莓派,前面写过一篇在树莓派上使用1602液晶显示屏,那么可以显示后最重要的就是显示什么的问题了. 最easy想到的就是显示时间啊,CPU利用率啊.IP地址之类的.那么我认为呢,假设可以显示当 ...

  2. Python学习笔记之模块与包

    一.模块 1.模块的概念 模块这一概念很大程度上是为了解决代码的可重用性而出现的,其实这一概念并没有多复杂,简单来说不过是一个后缀为 .py 的 Python 文件而已 例如,我在某个工作中经常需要打 ...

  3. [Python学习笔记]正则表达式总结

    常用缩写字符及其含义表格查询 缩写字符分类 含义 \d 0-9的任意数字 \D 除0-9的数字以外的任何字符 \w 任何字母.数字或下划线字符(可以认为是匹配"单词"字符) \W ...

  4. python学习笔记整理——字典

    python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...

  5. VS2013中Python学习笔记[Django Web的第一个网页]

    前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...

  6. python学习笔记之module && package

    个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...

  7. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  8. python学习笔记--Django入门四 管理站点--二

    接上一节  python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...

  9. python学习笔记--Django入门0 安装dangjo

    经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...

随机推荐

  1. Java8-Executors-No.01

    import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util ...

  2. P2461 [SDOI2008]递归数列 矩阵乘法+构造

    还好$QwQ$ 思路:矩阵快速幂 提交:1次 题解: 如图: 注意$n,m$如果小于$k$就不要快速幂了,直接算就行... #include<cstdio> #include<ios ...

  3. win下安装jupyter遇到的问题

    一:安装jupyter 1.首先要用管理员方式打开cmd,没用管理员打开后面安装不上. 2.安装jupyter.我用的是python3,所以用pip3 install jupyter进行安装. 3.安 ...

  4. Print工具类

    这篇文章已经废弃. 实际开发中,打印信息只会用日志框架(Log4j2). 受到Thinking in Java中静态引入(import static)的启发, Deolin也打算写一个方便自己的工具类 ...

  5. 1632:【 例 2】[NOIP2012]同余方程

    #include<bits/stdc++.h> #define ll long long using namespace std; void Exgcd(ll a,ll b,ll & ...

  6. c#简单的SQLHelp

    public abstract class SQLHelper { //只读的静态数据库连接字符串 //需添加引用System.Configuration; public static readonl ...

  7. easyui-combobox和C标签判断回显

    <td width="40%"> <select class="easyui-combobox" id="work_property ...

  8. COM 基础 之 三大基础接口

    摘自 http://blog.csdn.net/liang4/article/details/7530512 1 COM组件实际上是一个C++类,而接口都是纯虚类.组件从接口派生而来. 2 COM组件 ...

  9. java课后实验性问题1

    一.一个java类文件中只能有一个公有类吗? 测试代码 public class Test{ public static void main(String[] args){ } public clas ...

  10. Linux 系统配置永久性时间同步

    临时修改系统时间(reboot后系统时间恢复): date 查看系统时间 date -s  "设置的系统时间" 永久性修改系统时间: date 查看系统时间 hwclock --s ...