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