python學習筆記(2018.01.27)

終於把不顯示中文的問題搞好了,開心!

#coding = utf-8
import urllib.request
import json
from city import city

cityname = input('你想查詢哪個城市的天氣?\n')
citycode = city.get(cityname)
#print (citycode)
if citycode:
    try:
        url = ('http://www.weather.com.cn/data/cityinfo/%s.html' %citycode)  #構造網址
        content = urllib.request.urlopen(url).read().decode('utf-8')
        #讀取網頁源碼,decode(utf-8)JSON編碼的字符串轉換回Python數據結構
        #print (content)

        data = json.loads(content) #使用json庫將字符串轉化爲字典
        #print (data)
        result = data['weatherinfo']  #獲取字典
        #print (result)
        str_temp = ('%s\n%s~%s') %(
            result['weather'],  #天氣
            result['temp1'],  #最低溫
            result['temp2']  #最高溫
        )
        print (str_temp)  #輸出天氣信息
    except:
        print ('查詢失敗')
else:
    print ('沒有找到該城市')


用python中json模塊提供的loads方法,把它轉成一個真正的字典。

import json

data = json.loads(content)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章