需要用的鏈接和網址:
注冊免費API : http://console.heweather.com
國內城市ID : http://cdn.heweather.com/china-city-list.txt
介面:https://free-api.heweather.net/s6/weather/forecast?key=xxx&location=xxx
(key后的xxx填入key,location后的xxx填寫城市ID)
json編輯器: http://www.json.org.cn/tools/JSONEditorOnline/index.htm
首先,先注冊一個免費的API:
不會的可以看這個 傳送,做前兩個步驟就可以,
一:獲取國內城市資訊
import requests
url = 'http://cdn.heweather.com/china-city-list.txt' #國內城市ID
data = requests.get(url) #獲取網頁資料
data.encoding = 'utf8' #資料的編碼方式為utf8,否則會亂碼
print(data.text)
運行結果:

二: 處理資料
(1)前 6 行的資料是不需要的,應該洗掉

(2)在介面的鏈接中我們發現,還需要在localtion后填入城市ID,從輸出結果中可以看出,城市ID在每行的下標第2-12的位置,
import requests
url = 'http://cdn.heweather.com/china-city-list.txt' #國內城市ID
data = requests.get(url) #獲取網頁資料
data.encoding = 'utf8' #資料的編碼方式為utf8,否則會亂碼
data1 = data.text.split("\n") #通過split將文本轉換為串列
for i in range(6): #洗掉前6行不需要的資料
data1.remove(data1[0])
for item in data1: #找出城市ID
print(item[2:13])
運行結果:

三:獲取JSON格式的資料
import requests
import time
url = 'http://cdn.heweather.com/china-city-list.txt' #國內城市ID
data = requests.get(url) #獲取網頁資料
data.encoding = 'utf8' #資料的編碼方式為utf8,否則會亂碼
data1 = data.text.split("\n") #通過split將文本轉換為串列
for i in range(6): #洗掉前6行不需要的資料
data1.remove(data1[0])
for item in data1:
#介面鏈接中的key后面的xxx改為自己剛剛注冊的key,location后加上城市ID
url = 'https://free-api.heweather.net/s6/weather/forecast?key=xxx&location=' + item[2:13]
data2 = requests.get(url)
data2.encoding = 'utf8'
#time.sleep(1) #延時函式代碼,避免訪問服務器過于頻繁,每次訪問等待1s(這里可以不加)
print(data2.text)
運行結果:

四:決議JSON資料
(1)打開 JSON在線編輯器,觀察資料結構

(2)通過觀察路徑,列印需要的資訊,例如找出各城市當日的最高和最低氣溫
import requests
import time
url = 'http://cdn.heweather.com/china-city-list.txt' #國內城市ID
data = requests.get(url) #獲取網頁資料
data.encoding = 'utf8' #資料的編碼方式為utf8,否則會亂碼
data1 = data.text.split("\n") #通過split將文本轉換為串列
for i in range(6): #洗掉前6行不需要的資料
data1.remove(data1[0])
for item in data1:
#介面鏈接中的key后面的xxx改為自己剛剛注冊的key,location后加上城市ID
url = 'https://free-api.heweather.net/s6/weather/forecast?key=xxx&location=' + item[2:13]
data2 = requests.get(url)
data2.encoding = 'utf8'
#time.sleep(1) #避免訪問服務器過于頻繁,每次訪問等待1s(這里可以不加)
dic = data2.json()
for item in dic["HeWeather6"][0]["daily_forecast"][:1]: #[:1]只要今日天氣資訊
result = {
'城市':dic["HeWeather6"][0]["basic"]["location"],
'今日最高溫度':item["tmp_max"],
'今日最低溫度':item["tmp_min"]
}
print(result)
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/152680.html
標籤:其他
上一篇:幾個有用的python字串函式(format,join,split,startwith,endwith,lower,upper)
下一篇:羅馬數字轉整數 python
