Exemplo n.º 1
0
def queryWeather():
    cityname = input('输入你想要查询的城市:')
    citycode = city.get(cityname)

    # 调用查询接口
    if citycode:
        try:
            url = 'http://www.weather.com.cn/data/cityinfo/%s.html' % citycode
            content = urllib.request.urlopen(url).read().decode('utf-8')
            # 把json转换成字典格式
            data = json.loads(content)
            result = data['weatherinfo']
            str_temp = ('天气:%s\n温度:%s~%s') % (result['weather'],
                                              result['temp1'], result['temp2'])
            print(str_temp)

            # 保留查询记录,当前时间、城市、天气
            #f = open('天气查询记录.txt', 'a')
            #f.write(('%s\n%s\n%s\n') % (time.strftime('%Y-%m-%d', time.localtime(time.time())), cityname, str_temp))
            #f.close()
        except:
            print('查询失败!')

    else:
        print('没有找到您输入的城市!')
Exemplo n.º 2
0
def get_weather_2(cityname):
    print('\n接口 2:')
    citycode = city.get(cityname)
    if not citycode:
        print('未找到该城市')
        return
    url = 'http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % citycode
    print(url)
    resp = urllib.request.urlopen(url).read()
    # print(resp)
    # 因网页内容做了 gzip 压缩,所以要对其解压
    try:
        data = gzip.decompress(resp)
    except:
        data = resp
    # print(data)
    # 将 json 格式的结果转为字典对象
    result = json.loads(data)
    # print(result)
    result_data = result.get('data')
    # print(result_data)
    if result_data:
        print('当前温度:', result_data.get('wendu'), '℃')
        print('空气质量:', result_data.get('aqi'))
        print(result_data.get('ganmao'))
        print('天气预报:')
        forecast = result_data.get('forecast')
        for fc in forecast:
            print(fc.get('date'), ':', fc.get('type'), ',', fc.get('low'), ',',
                  fc.get('high'))
    else:
        print('未能获取此城市的天气情况。')
Exemplo n.º 3
0
def get_weather_2(cityname):
    print '\n接口 2:'
    citycode = city.get(cityname)
    if not citycode:
        print '未找到该城市'
        return
    url = 'http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % citycode
    print url
    resp = urllib2.urlopen(url).read()
    # print resp
    # 因网页内容做了 gzip 压缩,所以要对其解压
    try:
        buf = StringIO(resp)
        f = gzip.GzipFile(fileobj=buf)
        data = f.read()
    except:
        data = resp
    # print data
    # 将 json 格式的结果转为字典对象
    result = json.loads(data)
    # print result
    result_data = result.get('data')
    # print result_data
    if result_data:
        print '当前温度:', result_data.get('wendu'), '℃'
        print '空气质量:', result_data.get('aqi')
        print result_data.get('ganmao')
        # print result_data.get('ganmao').decode('utf-8')  # windows 编码参考
        print '天气预报:'
        forecast = result_data.get('forecast')
        for fc in forecast:
            print fc.get('date'), ':', fc.get('type'), ',', fc.get(
                'low'), ',', fc.get('high')
    else:
        print '未能获取此城市的天气情况。'
Exemplo n.º 4
0
def Get_weather():
    cityname = '北京'
    citycode = city.get(cityname)
    content = ' '
    while (True):
        if citycode:
            try:
                url = ('http://www.weather.com.cn/data/cityinfo/%s.html' %
                       citycode)
                content2 = urllib2.urlopen(url).read()
                if content != content2:
                    content = content2
                    data = json.loads(content)
                    result = data['weatherinfo']
                    str_temp = ('%s\n%s ~ %s') % (
                        result['weather'], result['temp1'], result['temp2'])
                    print str_temp
                    #Email_script.Post_Email(str_temp)
                else:
                    pass
                    #time.sleep(3*3600)

            except:
                print '查询失败'
        else:
            print '没有找到该城市'
Exemplo n.º 5
0
def get_weather_2(cityname):
    print('\n接口 2:')
    citycode = city.get(cityname)
    if not citycode:
        print('未找到该城市')
        return
    url = 'http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % citycode
    print(url)
    resp = requests.get(url)
    resp.encoding = 'utf8'
    result = resp.json()
    # print(result)
    result_data = result.get('data')
    # print(result_data)
    if result_data:
        print('当前温度:', result_data.get('wendu'), '℃')
        print('空气质量:', result_data.get('aqi'))
        print(result_data.get('ganmao'))
        print('天气预报:')
        forecast = result_data.get('forecast')
        for fc in forecast:
            print(fc.get('date'), ':', fc.get('type'), ',', fc.get('low'), ',',
                  fc.get('high'))
    else:
        print('未能获取此城市的天气情况。')
Exemplo n.º 6
0
def get_weather_2(cityname):
    print('\n接口 2:')
    citycode = city.get(cityname)
    if not citycode:
        print('未找到该城市')
        return
    url = 'http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % citycode
    print(url)
    resp = urllib.request.urlopen(url).read()
    # print(resp)
    # 因网页内容做了 gzip 压缩,所以要对其解压
    try:
        data = gzip.decompress(resp)
    except:
        data = resp
    # print(data)
    # 将 json 格式的结果转为字典对象
    result = json.loads(data)
    # print(result)
    result_data = result.get('data')
    # print(result_data)
    if result_data:
        print('当前温度:', result_data.get('wendu'), '℃')
        print('空气质量:', result_data.get('aqi'))
        print(result_data.get('ganmao'))
        print('天气预报:')
        forecast = result_data.get('forecast')
        for fc in forecast:
            print(fc.get('date'), ':', fc.get('type'), ',', fc.get('low'), ',', fc.get('high'))
    else:
        print('未能获取此城市的天气情况。')
Exemplo n.º 7
0
def get_weather_2(cityname):
    print '\n接口 2:'
    citycode = city.get(cityname)
    if not citycode:
        print '未找到该城市'
        return
    url = 'http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % citycode
    print url
    resp = urllib2.urlopen(url).read()
    # print resp
    # 因网页内容做了 gzip 压缩,所以要对其解压
    try:
        buf = StringIO(resp)
        f = gzip.GzipFile(fileobj=buf)
        data = f.read()
    except:
        data = resp
    # print data
    # 将 json 格式的结果转为字典对象
    result = json.loads(data)
    # print result
    result_data = result.get('data')
    # print result_data
    if result_data:
        print '当前温度:', result_data.get('wendu'), '℃'
        print '空气质量:', result_data.get('aqi')
        print result_data.get('ganmao')
        # print result_data.get('ganmao').decode('utf-8')  # windows 编码参考
        print '天气预报:'
        forecast = result_data.get('forecast')
        for fc in forecast:
            print fc.get('date'), ':', fc.get('type'), ',', fc.get('low'), ',', fc.get('high')
    else:
        print '未能获取此城市的天气情况。'
Exemplo n.º 8
0
def weather_report(cityname):
    citycode = city.get(cityname)
    url = 'http://www.weather.com.cn/data/cityinfo/%s.html' % citycode
    content = urllib2.urlopen(url).read()
    data = json.loads(content)
    result = data['weatherinfo']
    result_str = '%s\n:%s %s ~ %s' % (result['city'], result['weather'], result['temp2'], result['temp1'])
    return result_str
Exemplo n.º 9
0
def yuyin(msg):
    msg['Text'](msg['FileName'])
    yuyinname = msg['FileName']
    print(yuyinname)
    word1 = yuyinshibie(yuyinname)
    if '家' in word1 or '家庭' in word1:
        itchat.send('请稍等,宝贝!', msg['FromUserName'])
    if '进行监控' in word1:
        subprocess.Popen(
            'python3 /home/dachuan/PycharmProjects/untitled1/camera_reader.py',
            shell=True,
            stdout=subprocess.PIPE)
    if '谁' in word1 or '房间' in word1:
        fp = open('warning.txt', 'r')
        a = fp.read()
        fp.close()
        itchat.send('%s' % a, msg['FromUserName'])
        #subprocess.Popen('python3 /home/dachuan/PycharmProjects/untitled1/camera_reader.py',shell=True,stdout=subprocess.PIPE)

    if '天气' in word1 or '天' in word1:
        citycode = city.get('桂林')
        if citycode:
            url = ('http://www.weather.com.cn/data/cityinfo/%s.html' %
                   citycode)
            a = requests.get(url)
            itchat.send(a.content.decode('utf-8'), msg['FromUserName'])
    if '笑话' in word1 or '话' in word1 or '讲' in word1:
        itchat.send('请稍等,宝贝!', msg['FromUserName'])
        sendGreeting(msg)
    if '图片' in word1 or '美' in word1:
        a = random.randint(1, 5000)
        itchat.send('@img@%s' % '%s.jpg' % a, msg['FromUserName'])
    if '分析微信好友' in word1 or '分析' in word1 or '好友' in word1:
        friendList = itchat.get_friends(update=True)[1:]
        sexDict = {}
        total = len(friendList)
        print(friendList[0].keys())
        # print(friendList[0]['NickName'].encode('utf-8').decode())
        for friend in friendList:
            if not friend['Sex'] in sexDict:
                sexDict[friend['Sex']] = []
            sexDict[friend['Sex']].append(friend['NickName'] + ' ' +
                                          friend['DisplayName'])
            print(friend['PYInitial'])
        unkonw = len(sexDict[0])
        male = len(sexDict[1])
        female = len(sexDict[2])
        print('您共有%d位好友,其中未知性别好友%d,其中男性性别的好友%d位,女性性别的好友%d\n' %
              (total, unkonw, male, female))
        print('未知性别的好友是:\n')
        for name in sexDict[0]:
            print(name)
        print('男性的好友是:\n')
        for name in sexDict[1]:
            print(name)
        print('女性的好友是:\n')
        for name in sexDict[2]:
            print(name)
Exemplo n.º 10
0
def weatherQuery (cityName) :
    cityCode = city.get(cityName) ;     #dict.get(key, default=None) 第二个参数为查找不成功的返回值
    if (cityCode != None) :
        url = ('http://www.weather.com.cn/data/cityinfo/%s.html') %cityCode

        response = requests.get(url)
        data = json.loads(response.content.decode('utf8'))
        result = data['weatherinfo']
        str_temp = ("%s %s %s ~ %s") % (result['city'] , result['weather'] , result['temp1'] , result['temp2'])
        return str_temp
    else :
        return None
Exemplo n.º 11
0
def getCityWeather():
    cityname = input('你想查哪个城市的天气?\n')
    citycode = city.get(cityname)
    if citycode:
        url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
        content = urllib.request.urlopen(url).read()
        print('%s的天气是:%s' % [cityname, content])
    else:
        print('未找到')
        url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % '101010100')
        content = urllib.request.urlopen(url).read()
        print(content)
Exemplo n.º 12
0
def weatherQuery (cityName) :
    print cityName;
    cityCode = city.get(cityName) ;
    print cityCode
    url = ('http://www.weather.com.cn/data/cityinfo/%s.html') %cityCode

    response = requests.get(url)
    #print content
    #return content.decode('utf8')
    data = json.loads(response.content.decode('utf8'))
    result = data['weatherinfo']
    str_temp = ("%s %s %s ~ %s") % (result['city'] , result['weather'] , result['temp1'] , result['temp2'])
    #print str_temp
    return str_temp
Exemplo n.º 13
0
 def get_data_2(self, Dialog):
     citycode = city.get(self.lineEdit_2.text())
     url = ('http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % citycode)
     self.textEdit.setText('\n' + str(url))
     response = requests.request("GET", url)
     a = eval(response.content)
     forecast = a.get('data').get('forecast')
     self.textEdit.setText('                   ' +
                           a.get('data').get('city') + '\n'
                           '日期:' + forecast[0].get('date') + '\n'
                           '天气:' + forecast[0].get('type') + '\n'
                           '温度:' + forecast[0].get('low') + '~' +
                           forecast[0].get('high') + '℃\n'
                           '风向:' + forecast[0].get('fengxiang') + '\n'
                           '风级:' + forecast[0].get('fengli') + '\n'
                           '感冒:' + a.get('data').get('ganmao') + '\n\n')
Exemplo n.º 14
0
def __getCityWeatherApi__(cityname):    
    citycode = city.get(cityname)
    if citycode:
        try:
            web = urllib.request.urlopen('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
            content = str(web.read(),'utf-8')
            data = json.loads(content)
            result = data['weatherinfo']
            str_temp = ('%s\n%s ~ %s')%(
                result['weather'],
                result['temp1'],
                result['temp2']
                )
            return str_temp
        except:
            return 'err'
    else:
        return 'no such city'
Exemplo n.º 15
0
def get_weather_1(cityname):
    print('\n接口 1:')
    citycode = city.get(cityname)
    if not citycode:
        print('未找到该城市')
        return
    url = 'http://www.weather.com.cn/data/cityinfo/%s.html' % citycode
    print(url)
    resp = requests.get(url)
    resp.encoding = 'utf8'
    result = resp.json()
    # print(result)
    result_data = result.get('weatherinfo')
    # print(result_data)
    if result_data:
        print('天气:', result_data.get('weather'))
        print('最低温度:', result_data.get('temp1'))
        print('最高温度:', result_data.get('temp2'))
    else:
        print('未能获取此城市的天气情况。')
Exemplo n.º 16
0
def get_weather_1(cityname):
    print('\n接口 1:')
    citycode = city.get(cityname)
    if not citycode:
        print('未找到该城市')
        return
    url = 'http://www.weather.com.cn/data/cityinfo/%s.html' % citycode
    print(url)
    resp = requests.get(url)
    resp.encoding = 'utf8'
    result = resp.json()
    # print(result)
    result_data = result.get('weatherinfo')
    # print(result_data)
    if result_data:
        print('天气:', result_data.get('weather'))
        print('最低温度:', result_data.get('temp1'))
        print('最高温度:', result_data.get('temp2'))
    else:
        print('未能获取此城市的天气情况。')
Exemplo n.º 17
0
def get_weather_1(cityname):
    print '\n接口 1:'
    citycode = city.get(cityname)
    if not citycode:
        print '未找到该城市'
        return
    url = 'http://www.weather.com.cn/data/cityinfo/%s.html' % citycode
    print url
    resp = urllib2.urlopen(url).read()
    # print resp
    # 将 json 格式的结果转为字典对象
    result = json.loads(resp)
    # print result
    result_data = result.get('weatherinfo')
    # print result_data
    if result_data:
        print '天气:', result_data.get('weather')
        print '最低温度:', result_data.get('temp1')
        print '最高温度:', result_data.get('temp2')
    else:
        print '未能获取此城市的天气情况。'
Exemplo n.º 18
0
def get_weather_1(cityname):
    print('\n接口 1:')
    citycode = city.get(cityname)
    if not citycode:
        print('未找到该城市')
        return
    url = 'http://www.weather.com.cn/data/cityinfo/%s.html' % citycode
    print(url)
    resp = urllib.request.urlopen(url).read()
    # print(resp)
    # 将 json 格式的结果转为字典对象
    result = json.loads(resp)
    # print(result)
    result_data = result.get('weatherinfo')
    # print(result_data)
    if result_data:
        print('天气:', result_data.get('weather'))
        print('最低温度:', result_data.get('temp1'))
        print('最高温度:', result_data.get('temp2'))
    else:
        print('未能获取此城市的天气情况。')
Exemplo n.º 19
0
def text_reply(msg):
    if '我爱你' in msg['Text'] and msg['FromUserName']:
        itchat.send('我也爱你,宝贝!', msg['FromUserName'])
        a = random.randint(1, 5000)
        itchat.send('@img@%s' % '%s.jpg' % a, msg['FromUserName'])
        sendGreeting(msg)

    if '天气' in msg['Text'] and msg['FromUserName']:
        citycode = city.get(msg['Text'][3:])
        if citycode:
            url = ('http://www.weather.com.cn/data/cityinfo/%s.html' %
                   citycode)
            a = requests.get(url)
            itchat.send(a.content.decode('utf-8'), msg['FromUserName'])

    if '下载' in msg['Text'] and msg['FromUserName']:
        print(filename)
        itchat.send('@img@%s' % filename, msg['FromUserName'])
    if '全部' in msg['Text'] and msg['FromUserName']:
        for filename1 in picture:
            itchat.send('@img@%s' % filename1, msg['FromUserName'])
Exemplo n.º 20
0
def main():
    print '|--------------------欢迎使用天气查询系统-----------------------|'
    print '|---------------------designed by Snowood-----------------------|'
    cityname = raw_input('你想查哪个城市的天气?\n')
    citycode = city.get(cityname)  # 从city.py文件获取城市的id值
    if citycode:  # 如果查到了id
        url = ('http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % citycode)
        req = urllib2.urlopen(url)
        info = req.info()  # 获取返回头信息
        # print info
        encoding = info.getheader('Content-Encoding')
        content = req.read()
        if encoding == 'gzip':  # 如果网页被gzip压缩,先解压
            buf = StringIO(content)
            gf = gzip.GzipFile(fileobj=buf)
            content = gf.read()
        data = json.loads(content)['data']  # 将json数据转成字典
        ganmao = data['ganmao']

        day = dict()
        for i in range(5):
            day[i] = data['forecast'][i]
        yesterday = data['yesterday']
        display_weather(day[0], 0)
        print ganmao  # 感冒的几率
        display_yesterday = raw_input('是否显示昨天天气?(y/n)\n')
        if display_yesterday == 'y':
            display_weather(yesterday, -1)
        display_next4 = raw_input('是否显示未来四天天气?(y/n)\n')
        if display_next4 == 'y':
            for i in range(1, 5):
                display_weather(day[i], i)

        print '|--------------------谢谢使用天气查询系统!----------------------|'
    else:
        print '|-------------------- 输入的城市名称有误!----------------------|'
Exemplo n.º 21
0
def weather():
	exit = False
	while not exit:
		cityname = raw_input("which city\'s weather do you want to get?\n")
		if cityname != 'n':
			citycode = city.get(cityname)
			if citycode:
				try:
					url = 'http://www.weather.com.cn/data/cityinfo/%s.html'%citycode
					content = urllib2.urlopen(url).read()
					data = json.loads(content)
					result = data['weatherinfo']
					str_temp = ('%s\n%s ~ %s') %(
							result['weather'],
							result['temp1'],
							result['temp2']
							)
					print (str_temp)
				except:
					print('查询失败')
			else:
				print('没有找到该城市')
		else:
			exit = True
Exemplo n.º 22
0
def get_weather_2(cityname):
    print('\n接口 2:')
    citycode = city.get(cityname)
    if not citycode:
        print('未找到该城市')
        return
    url = 'http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % citycode
    print(url)
    resp = requests.get(url)
    resp.encoding = 'utf8'
    result = resp.json()
    # print(result)
    result_data = result.get('data')
    # print(result_data)
    if result_data:
        print('当前温度:', result_data.get('wendu'), '℃')
        print('空气质量:', result_data.get('aqi'))
        print(result_data.get('ganmao'))
        print('天气预报:')
        forecast = result_data.get('forecast')
        for fc in forecast:
            print(fc.get('date'), ':', fc.get('type'), ',', fc.get('low'), ',', fc.get('high'))
    else:
        print('未能获取此城市的天气情况。')
Exemplo n.º 23
0
#coding:utf-8
import urllib2
import json
from city import city

cityname = raw_input('City Name Please:')
city_nu = city.get(cityname)
if city_nu:
    url = 'http://www.weather.com.cn/data/cityinfo/'+city_nu+'.html'
    web = urllib2.urlopen(url)
    data = json.loads(web.read())
    # weather to read
    info = data['weatherinfo']
    print ' %s To day\n %s %s ~ %s'%(info['city'],info['weather'],info['temp1'],info['temp2']) 
else:
    print '404 city not found'
Exemplo n.º 24
0
#coding:utf-8
import urllib2
from city import city
import json

cityName = raw_input("请输入查询天气的城市")
cityCode = city.get(cityName)
if cityCode:
    url = ("http://www.weather.com.cn/data/cityinfo/%s.html" % cityCode)
    content = urllib2.urlopen(url).read()
    data = json.loads(content)
    weather_dict = data["weatherinfo"]
    high = u"最高温度:" + weather_dict["temp1"]
    low = u"最低温度:" + weather_dict["temp2"]
    weather = u"天气:" + weather_dict["weather"]
    time = u"时间:" + weather_dict["ptime"]
    list = [cityName, high, low, weather, time]
    for sub in list:
        print sub + "\n"
Exemplo n.º 25
0
#coding:utf-8
import urllib2
import json
from city import city

city_name = raw_input('你想查询哪个城市的天气:\n')
city_code = city.get(city_name)

if city_code:
    url = ('http://www.weather.com.cn/weather/%s.shtml' % city_code)
    web = urllib2.urlopen(url)
    content = web.read()
    print content
Exemplo n.º 26
0
#_*_coding:utf-8_*_
import urllib2
import json
from city import city
cityName = raw_input ("Please input the CityName of the Weather you want to know:") ;

cityCode = city.get(cityName) ;

url = ('http://www.weather.com.cn/data/cityinfo/%s.html') %cityCode

content = urllib2.urlopen(url).read()

data = json.loads(content)
result = data['weatherinfo']
str_temp = ("%s %s %s ~ %s") % (result['city'] , result['weather'] , result['temp1'] , result['temp2'])

print (str_temp)
Exemplo n.º 27
0
from city import city
import urllib.request
import json

yourcity=input()
citycode=city.get(yourcity)
if citycode:
    url=('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
    content=urllib.request.urlopen(url).read()
    
else:
    print('default')
data=json.loads(content)
result=data['weatherinfo']
str_temp=('%s\n%s~%s'%(result['weather'],result['temp1'],result['temp2']))
print(str_temp)
Exemplo n.º 28
0
# -*-coding:utf8-*-
import requests
import sys
from city import city
reload(sys)
sys.setdefaultencoding('utf-8')
try:
    while True:
        city_name = raw_input('输入你要查询的城市:\n')
        if not city_name:
            break
        if city_name in city.keys():
            city_num = city.get(city_name)
            url = 'http://www.weather.com.cn/data/cityinfo/101%s.html' % city_num
            result = requests.get(url)
            data = result.json()
            results = data['weatherinfo'].values()
            cityname = results[0].encode('raw_unicode_escape')
            weather = results[5].encode('raw_unicode_escape')
            temp2 = results[3].encode('raw_unicode_escape')
            temp1 = results[4].encode('raw_unicode_escape')
            print """城市:%s
天气:%s
最高气温:%s
最低气温:%s
""" % (cityname, weather, temp2, temp1)
        else:
            print "没有该城市天气预报"
except:
    print "网页请求错误!"
Exemplo n.º 29
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Filename: weather.py

from city import city
import urllib2

cityname = raw_input('Which city do you want to know?\n')
citycode = city.get(cityname)
print citycode
if citycode:
    url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
    content = urllib2.urlopen(url).read()
    print content
Exemplo n.º 30
0
proxy_support = urllib2.ProxyHandler(
    {"http": "http://%(host)s:%(port)d" % proxy_info})

opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

reload(sys)
sys.setdefaultencoding('utf-8')
s = u'城市名称:\n'
cityname = raw_input(s.encode('gb2312'))
#cityname = raw_input(s)
#cityname1=cityname.encode("gb2312")
print(cityname.decode('gbk').encode('utf-8'))
#print(cityname.encode('utf-8'))
#citycode = city.get(cityname.decode('gb2312').encode('gb2312'))
citycode = city.get(cityname.decode('gbk').encode('utf-8'))
print(citycode)

#html=urllib2.urlopen("http://172.24.208.168/#", timeout=60).read()
#print(html)

if citycode:
    url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
    content = urllib2.urlopen(url, timeout=30).read()
    print content

#print city
raw_input()
#data=json.loads(content)
#re=data['weatherinfo']
Exemplo n.º 31
0
#! /usr/bin/python
##-*- coding: utf-8 -*-

import urllib2
import json
from city import city
#from a import city
cityname = raw_input('city name ?\n')
citycode = city.get(cityname)
if citycode:
    try:
        url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
        content = urllib2.urlopen(url).read()
        #print content
        data = json.loads(content)
        result = data['weatherinfo']
        str_temp = ('%s: %s ~ %s') % (result['weather'], result['temp1'],
                                      result['temp2'])

        print str_temp
    except:
        print 'failed'
else:
    print 'no city'
#print type(content)
#print type(data)
Exemplo n.º 32
0
# -*- coding: utf-8 -*-
import json
import urllib.request
import zlib

from city import city

city_name = input('输入:\n')
city_code = city.get(city_name)


if city_code:
	try:
		url = ('http://wthrcdn.etouch.cn/weather_mini?citykey=%s' % city_code)
		content = urllib.request.urlopen(url)
		html = content.read()
		response = zlib.decompress(html, 16 + zlib.MAX_WBITS)
		u = response.decode('utf-8')
		dict_json = json.loads(u)  # 将json格式转化为字典
		weather = dict_json['data']
		sit = weather['forecast']
		print("城市:", weather['city'])
		print("提示:\n", weather['ganmao'])
		for t in sit[0].keys():
			print(sit[0][t], end=' ')
	except Exception as e:
		print("错误!!", e)
else:
	print('没有该城市')