国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現自主查詢實時天氣

2020-02-15 21:58:41
字體:
來源:轉載
供稿:網友

本文實例為大家分享了python實現自主查詢實時天氣的具體代碼,供大家參考,具體內容如下

用到了urllib2 json  很簡單的一個應用 如下

獲取城市編號

#coding=utf-8 import urllib2  url1 = 'http://m.weather.com.cn/data3/city.xml' content1 = urllib2.urlopen(url1).read() provinces = content1.split(',') print content1 # 輸出content1可以查看全部省份代碼 result = '' url = 'http://m.weather.com.cn/data3/city%s.xml' for p in provinces:   p_code = p.split('|')[0]   url2 = url % p_code   content2 = urllib2.urlopen(url2).read() # 輸出content2可以查看此省份下所有城市代碼   cities = content2.split(',')   print content2   for c in cities:     c_code = c.split('|')[0]     url3 = url % c_code     content3 = urllib2.urlopen(url3).read()     print content3 #content3是此城市下所有地區代碼     districts = content3.split(',')     for d in districts: # 對于每個地區,我們把它的名字記錄下來,然后再發送一次請求,得到它的最終代碼:       d_pair = d.split('|')       d_code = d_pair[0] #       if 5 == len(d_code):         continue         temp=[d_code]         temp.insert(4,0)         d_code ="".join(temp)       name = d_pair[1] # 名字       url4 = url % d_code       content4 = urllib2.urlopen(url4).read()       print content4       code = content4.split('|')[1]       line = "%s:%s/n" % (name, code)       result += line       print name + ':' + code f = file('./city', 'w') f.write(result) f.close() 

findweather

# -*- coding: utf-8 -*- import urllib2 import json city = {} f =file('city','r') src = f.readlines() for line in src:   line = line.split('/n')[0]   name = line.split(':')[0]   code = line.split(':')[1]   city[name] = code cityname = raw_input('請輸入你要查詢的城市名稱:/n') citycode = city.get(cityname) print 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 '沒有找到該城市' 

運行 findweather  即可。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 永宁县| 漯河市| 肥东县| 云龙县| 云林县| 东明县| 海丰县| 丰城市| 包头市| 义乌市| 永吉县| 常德市| 潍坊市| 富裕县| 北川| 桑日县| 图片| 玛曲县| 孝昌县| 唐山市| 惠水县| 西和县| 保康县| 江北区| 孙吴县| 常德市| 罗田县| 台前县| 郧西县| 高要市| 修武县| 象山县| 襄垣县| 堆龙德庆县| 芮城县| 玉树县| 图们市| 江口县| 潮安县| 云梦县| 佳木斯市|