current position:Home>Python realizes weather query function

Python realizes weather query function

2022-01-31 21:55:55 ZackSock

This is my participation 11 The fourth of the yuegengwen challenge 4 God , Check out the activity details :2021 One last more challenge

One 、 Introduce

Let's first look at the functions of the implemented program :  Insert picture description here The function is also very simple , Input City , Display current city 、 Current date time 、 Temperature and weather .

API Using the interface of the National Meteorological Administration , Completely free : t.weather.sojson.com/api/weather… This is the interface taking Beijing as an example , The last number 101010100 It's the city code of Beijing . To query other cities, you only need to modify the city code to that of other cities .

Because of this API Can only be accessed through the city code , There is still a little trouble in this regard , But I sorted out a city code json file , I'll explain this process later .

Two 、 Return the data

Take Nanchang as an example , Because there is a lot of data returned , It's an incomplete list . When the request is successful , The approximate data are as follows :  Insert picture description here There are still many places in it that haven't been opened , Then we try to access a wrong city code : t.weather.sojson.com/api/weather… among 1 It's an illegal city code , Let's take a look at the data :

{
    "message": "Request resource not found.",
    "status": 404
}
 Copy code 

Both have one status, That's the status code . When the status code is 200 when , Indicates that the request completed normally .404 That's what we often see , It means I didn't find .

Two 、 Code explanation

The code is very simple , It mainly uses two modules :requests、json. A network request , One json analysis .

import requests, json

#api Address 
url = 'http://t.weather.sojson.com/api/weather/city/'

# Enter city Chinese 
city = input(" Please enter the city you want to query :")

# Read json file 
f = open('city.json', 'rb')

# Use json Modular load Method loading json data , Return a dictionary 
cities = json.load(f)

# Get the city code through the Chinese of the city 
city = cities.get(city)

# Network request , incoming request api+ City Code 
response = requests.get(url + city)

# Taking data to json returns , This d It's back json data 
d = response.json()

# When the return status code is 200, Output weather conditions 
if(d['status'] == 200):
    print(" City :", d["cityInfo"]["parent"], d["cityInfo"]["city"])
    print(" Time :", d["time"], d["data"]["forecast"][0]["week"])
    print(" temperature :", d["data"]["forecast"][0]["high"], d["data"]["forecast"][0]["low"])
    print(" The weather :", d["data"]["forecast"][0]["type"])
 Copy code 

There's nothing particularly difficult about code , You need to be right when outputting json Have some knowledge of the data , Then according to their own needs , Just output . You can try to ask , And then use HiJson Format it , Or there are many web sites formatted online , Then analyze the data you need .

3、 ... and 、 Change the city code to json data (Excel skill )

Next, let's talk about my struggle with the city code as follows , You don't have to look at the following paragraph . Used in the code city.json I'll upload the file at the end of the text .

Because I didn't find the interface to get the city code , Only the following text was found :

 Beijing :101010100 The rising sun :101010300 Shunyi :101010400 Huairou :101010500 Tongzhou :101010600 Changping :101010700 Yanqing :101010800 fengtai :101010900 Shijingshan :101011000 Daxing :101011100 Fangshan :101011200 Miyun :101011300 Mentougou :101011400 Pinggu :101011500 badaling section of the great wall :101011600 Foyeding :101011700 Tanghekou :101011800 Miyun Shangdianzi :101011900 Vegetarian Canteen :101012000 Xiayunling :101012100 Beijing City :101012200 haidian :101010200 tianjin :101030100 Baodi :101030300 Dongli :101030400 Xiqing :101030500 Beichen :101030600 Jixian County :101031400 Hangu :101030800 Jinghai :101030900 Jinnan :101031000 Tanggu :101031100 Dagang :101031200 Wuqing :101030200 Ninghe :101030700 Shanghai :101020100 baoshan :101020300 Jiading :101020500 Nanhui :101020600 In the pudong new area :101021300 Qingpu :101020800 Songjiang :101020900 Fengxian :101021000 Chongming :101021100 Xu Jiahui :101021200 Minhang :101020200 jinshan :101020700 shijiazhuang :101090101 zhangjiakou :101090301 chengde :101090402 Tangshan :101090501 qinhuangdao :101091101 Cangzhou :101090701 hengshui :101090801 xingtai :101090901 handan :101091001 baoding :101090201 langfang :101090601 zhengzhou :101180101 xinxiang :101180301 xuchang :101180401 Pingdingshan :101180501 Xinyang :101180601 Nanyang :101180701 kaifeng :101180801 luoyang :101180901 Shangqiu :101181001 Jiaozuo :101181101 Hebi :101181201 Puyang :101181301 Zhoukou :101181401 Luohe :101181501 Zhumadian :101181601 Sanmenxia :101181701 Jiyuan :101181801 anyang :101180201 Hefei :101220101 wuhu :101220301 Huainan :101220401 Ma'anshan :101220501 Anqing :101220601 Suzhou :101220701 Fuyang :101220801 Bozhou :101220901 huangshan :101221001 chuzhou :101221101 Huaibei :101221201 Tongling :101221301 xuancheng :101221401 Lu'an :101221501 Chaohu Lake :101221601 Chizhou :101221701 Bengbu :101220201 Hangzhou :101210101 zhoushan :101211101 huzhou :101210201 jiaxing :101210301 jinhua :101210901 shaoxing :101210501 Taizhou :101210601 wenzhou :101210701 Lishui :101210801 Quzhou :101211001 ningbo :101210401 Chongqing :101040100 Hechuan :101040300 Nanchuan :101040400 Jiangjin :101040500 Wansheng :101040600 Yubei :101040700 beibei :101040800 Banan :101040900 longevity :101041000 Qianjiang :101041100 Wanzhou Tiancheng :101041200 Wanzhou Longbao :101041300 Fuling :101041400 Kaixian :101041500 Chengkou :101041600 Yunyang :101041700 Wuxi :101041800 Fengjie :101041900 Wushan :101042000 Tongnan :101042100 Dianjiang :101042200 Liang Ping :101042300 Zhongxian :101042400 Stone :101042500 Dazu :101042600 Rongchang :101042700 Tongliang :101042800 Bishan :101042900 Fengdu :101043000 Wulong :101043100 Pengshui :101043200 Qijiang :101043300 Youyang :101043400 Xiushan :101043600 Shapingba :101043700 Yongchuan :101040200 fuzhou :101230101 quanzhou :101230501 zhangzhou :101230601 longyan :101230701 Jinjiang :101230509 Nanping :101230901 Xiamen :101230201 Ningde :101230301 Putian :101230401 Sanming :101230801 lanzhou :101160101 Of out :101160301 Qingyang :101160401 Wuwei :101160501 Jinchang :101160601 Jiayuguan :101161401 jiuquan :101160801 tianshui :101160901 Arms are :101161001 Linxia :101161101 cooperation :101161201 Silver :101161301 Dingxi :101160201 Zhangye :101160701 Guangzhou :101280101 huizhou :101280301 Meizhou :101280401 Shantou :101280501 Shenzhen :101280601 zhuhai :101280701 foshan :101280800 zhaoqing :101280901 zhanjiang :101281001 Jiangmen :101281101 Heyuan :101281201 qingyuan :101281301 The clouds are floating :101281401 Chaozhou :101281501 dongguan :101281601 zhongshan :101281701 Yangjiang :101281801 Jieyang :101281901 Maoming :101282001 Shanwei :101282101 Shaoguan :101280201 nanning :101300101 Liuzhou :101300301 Guest :101300401 guilin :101300501 Wuzhou :101300601 port of fangcheng :101301401 Guigang :101300801 Yulin :101300901 Baise :101301001 Qinzhou :101301101 Rivers and pools :101301201 The north sea :101301301 Chongzuo :101300201 Hezhou :101300701 guiyang :101260101 Anshun :101260301 Duyun :101260401 Xingyi :101260906 Tongren :101260601 Bijie :101260701 Liupanshui :101260801 zunyi :101260201 Kerry :101260501 kunming :101290101 Red River :101290301 Wenshan :101290601 Yuxi :101290701 Chuxiong :101290801 Pu 'er Tea :101290901 Zhaotong :101291001 lincang :101291101 nu :101291201 shangri-la :101291301 Lijiang :101291401 dehong :101291501 jinghong :101291601 Dali :101290201 Qujing :101290401 baoshan :101290501 Hohhot, :101080101 The wuhai :101080301 JiNing :101080401 Tongliao :101080501 Alashan Left Banner :101081201 ordos :101080701 linhe :101080801 Xilinhaote :101080901 The hulunbuir :101081000 Ulanhot :101081101 baotou :101080201 Chifeng :101080601 nanchang :101240101 shangrao :101240301 Fuzhou :101240401 Yichun :101240501 yingtan :101241101 Ganzhou :101240701 Jingdezhen :101240801 Pingxiang :101240901 Xinyu :101241001 Jiujiang :101240201 Ji'an :101240601 wuhan :101200101 huanggang :101200501 jingzhou :101200801 yichang :101200901 enshi :101201001 Shiyan :101201101 shennongjia :101201201 Suizhou :101201301 Jingmen :101201401 Tianmen :101201501 Xiantao :101201601 Qianjiang :101201701 Xiangfan :101200201 Ezhou :101200301 Xiaogan :101200401 Yellowstone :101200601 xianning :101200701 Chengdu :101270101 Zigong :101270301 mianyang :101270401 nanchong :101270501 dazhou :101270601 Suining :101270701 Guang'an :101270801 Bazhong :101270901 Luzhou :101271001 Yibin :101271101 Neijiang :101271201 Ziyang :101271301 leshan :101271401 meishan :101271501 Liangshan :101271601 Ya'an :101271701 Ganzi :101271801 ABA :101271901 deyang :101272001 Guangyuan :101272101 Panzhihua :101270201 yinchuan :101170101 Zhongwei :101170501 Guyuan :101170401 Shizuishan :101170201 Wu Zhong :101170301 xining :101150101 Huang Nan :101150301 Haibei :101150801 GOLO :101150501 yushu :101150601 Haixi :101150701 Haidong :101150201 hainan :101150401 jinan :101120101 weifang :101120601 Linyi :101120901 Heze :101121001 Binzhou :101121101 dongying :101121201 weihai :101121301 Zaozhuang :101121401 sunshine :101121501 Laiwu :101121601 Liaocheng :101121701 Qingdao :101120201 zibo :101120301 Texas :101120401 yantai :101120501 Jining :101120701 Taian :101120801 Xi'an :101110101 yanan :101110300 Yulin :101110401 Tongchuan :101111001 Shangluo :101110601 Well being :101110701 Hanzhong city :101110801 baoji :101110901 xianyang :101110200 Weinan :101110501 taiyuan :101100101 Linfen :101100701 yuncheng :101100801 It is mined here :101100901 Xinzhou :101101001 changzhi :101100501 datong :101100201 Yangquan :101100301 jinzhong :101100401 jincheng :101100601 Lvliang :101101100 urumqi :101130101 Shihezi :101130301 Changji :101130401 Turpan :101130501 Korla :101130601 Alar :101130701 Akesu :101130801 Kashgar :101130901 Yining :101131001 Tuscaloosa :101131101 hami :101131201 Hotan :101131301 altay :101131401 Atush :101131501 Bole :101131601 karamay :101130201 Lhasa :101140101 Shannan :101140301 Ali :101140701 changdu :101140501 Naqu :101140601 Shigatse :101140201 nyingchi :101140401 Taipei County :101340101 Kaohsiung :101340201 Taichung :101340401 haikou :101310101 sanya :101310201 The east :101310202 In the high :101310203 ChengMai :101310204 danzhou :101310205 Changjiang :101310206 Baisha :101310207 QiongZhong :101310208 anding :101310209 Tunchang :101310210 qionghai :101310211 wenchang :101310212 BaoTing :101310214 mannings :101310215 lingshui :101310216 Xisha :101310217 Nansha Island :101310220 ledong :101310221 wuzhishan :101310222 Qiongshan :101310102 Changsha :101250101 zhuzhou :101250301 city in Hunan :101250401 Chenzhou :101250501 changde :101250601 Yiyang :101250700 Loudi :101250801 Shaoyang :101250901 Yueyang :101251001 zhangjiajie :101251101 Huaihua :101251201 Qianyang :101251301 yongzhou :101251401 Jishou :101251501 xiangtan :101250201 nanjing :101190101 zhenjiang :101190301 Suzhou :101190401 nantong :101190501 yangzhou :101190601 Suqian :101191301 xuzhou :101190801 huaian :101190901 lianyungang :101191001 changzhou :101191101 Taizhou :101191201 wuxi :101190201 yancheng :101190701 Harbin :101050101 Mudanjiang :101050301 Jiamusi :101050401 Suihua :101050501 Heihe :101050601 Shuangyashan :101051301 Yichun :101050801 Daqing :101050901 Qitaihe River :101051002 Jixi :101051101 Hegang :101051201 Qiqihar :101050201 Greater Khingan Range :101050701 changchun :101060101 Yanji :101060301 Siping :101060401 mount bai :101060901 Baicheng :101060601 Liaoyuan :101060701 Songyuan :101060801 Ji Lin :101060201 Tonghua :101060501 shenyang :101070101 Anshan :101070301 Fushun :101070401 Benxi :101070501 Dandong :101070601 Huludao :101071401 Yingkou :101070801 Fuxin :101070901 Liaoyang :101071001 Tieling :101071101 The rising sun :101071201 Panjin :101071301 dalian :101070201 Jinzhou :101070701 
 Copy code 

Copy this text first , Then open the Excel, Select a unit , Paste . It will have the following effects :  Insert picture description here Then we click on Beijing , Drag the horizontal scroll bar , Hold down shift, Click on the last data :  Insert picture description here In this way, the whole data is selected . And then copy it , Click on a cell below Beijing . Right click -> Selective replication -> Check transpose :  Insert picture description here The effect after transposition is as follows , Insert picture description here But there is an obvious problem , Beijing corresponds to 101010100. And above are Chaoyang and 101010100 together , And in the same cell . Let's split the data into two cells . stay “101010100 The rising sun ” Cell , Choose “101010100”. Copy to the right ( Note that you should first set the format to text ): Cell 1, Re selection “ The rising sun ”, Copy to next cell : Cell 2, Then click on each cell 1、 Cell 2, Press ctrl+E, It has the following effects :  Insert picture description here

The data are separated , Then we delete the redundant data . We select the data in the left column ( Let's start , Press shift, Point end ), shear , Then click on the previous cell , Copy :  Insert picture description here Then it's aligned , Now let's put it back . Click on the top left corner 、 Hold down shift、 Click on the bottom right corner ( Areas with data ), And then copy it -> Click on a blank cell -> Paste special -> Transposition : Insert picture description here I'll swap the two lines , Then transposed . After transpose , We will use valid data ( Horizontal data ) Copy . Then open the browser : www.bejson.com/json/col2js… Use this URL , Copy the content in , Just click the conversion . The effect is as follows , We just need to put json Just save the text in a file . Insert picture description here although API Your request is really very convenient , But it's really troublesome to code this city .

Code and files also use HiJson I have uploaded Baidu cloud : link :pan.baidu.com/s/1_sGBFm0N… Extraction code :o5ay

Some time ago , A friend provided a city code interface in the comments . There are still some problems in the process of use , Then I looked again , Found another interface : wthrcdn.etouch.cn/weather_min… This interface does not need to pass city code , Just pass in the city name directly . Then the code can be changed to :

import requests, json

weatherUrl = "http://wthrcdn.etouch.cn/WeatherApi?city="        # return xml data 
weatherUrl = "http://wthrcdn.etouch.cn/weather_mini?city="      # return json data 

cityName = input(" Please enter the city you want to query :")

weatherResp = requests.get(weatherUrl + cityName)
d = weatherResp.json()

if(d['status'] >= 1000):
    print(" City :", d["data"]["city"])
    print(" Time :", d["data"]["forecast"][0]["date"])
    print(" temperature :", d["data"]["forecast"][0]["high"], d["data"]["forecast"][0]["low"])
    print(" The weather :", d["data"]["forecast"][0]["type"])
 Copy code 

Because the data returned by this structure is normal 1000, So the judgment is changed to ==1000. It's much more convenient at once ~

copyright notice
author[ZackSock],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201312155503190.html

Random recommended