国产探花免费观看_亚洲丰满少妇自慰呻吟_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  即可。

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 广丰县| 桃园市| 图木舒克市| 定结县| 城步| 通辽市| 大同县| 利辛县| 灵宝市| 龙口市| 洪洞县| 中西区| 涟水县| 钦州市| 和田市| 根河市| 电白县| 忻城县| 阜平县| 阿合奇县| 乐陵市| 南昌县| 秦皇岛市| 玉林市| 杭锦后旗| 聂荣县| 崇州市| 瑞丽市| 平阴县| 大城县| 临夏市| 长垣县| 土默特左旗| 花莲市| 渝北区| 绥德县| 米易县| 桐乡市| 交城县| 宜宾县| 衡南县|