文 / 秦未
大家好!好久沒寫文章了,我昨天晚上搗騰JS實現天氣的方法,由于本人JS并沒有學好,遇到一個問題,始終無法解決,學前端的童鞋如果懂一點相關的知識,可以幫忙解決嗎?問題在文章末尾。
最后如標題所示,我還是用Python來得到數據算了,由于自己用阿里云的服務器,所以就在阿里云找了一個免費的天氣API接口,0元一年一萬次調用,雖然不夠用,但是應該能湊合十多天了。
20170615101818.png
購買地址:https://market.aliyun.com/products/57126001/cmapi014302.html#sku=yuncode830200000
它提供的方法是Python2的調用方法:
import urllib, urllib2, sys
host = 'http://jisutqybmf.market.alicloudapi.com'
path = '/weather/query'
method = 'GET'
appcode = '你自己的AppCode'
querys = 'city=%E5%AE%89%E9%A1%BA&citycode=citycode&cityid=cityid&ip=ip&location=location'
bodys = {}
url = host + path + '?' + querys
request = urllib2.Request(url)
request.add_header('Authorization', 'APPCODE ' + appcode)
response = urllib2.urlopen(request)
content = response.read()
if (content):
print(content)
在Python3中urllib與urllib2已經合并成urllib,但是我并沒有使用這個模塊,而是使用了Requests模塊,相信很多學爬蟲的同學一定聽說并使用過它了,沒聽說過的同學也不用擔心,因為它足夠簡單,只要閱讀一下官方文檔即可快速使用它。
附上中文文檔:快速上手 — Requests 2.10.0 文檔
使用它自然要先安裝了,安裝命令(管理員權限):
pip install requests
下面就是修改完畢的代碼(AppCode位置:控制臺/云市場/API):
import requests
def get_weather(city):
url = 'http://jisutqybmf.market.alicloudapi.com/weather/query'
appcode = '你自己的AppCode '
headers = {'Authorization': 'APPCODE ' + appcode}
try:
content = requests.get(url=url, params={'city': city}, headers=headers)
except requests.exceptions.Timeout:
return 'TimeoutError'
except requests.exceptions.ConnectionError:
return 'ConnectionError'
except requests.exceptions.HTTPError:
return 'HTTPError'
except requests.exceptions.TooManyRedirects:
return 'TooManyRedirects'
except:
return 'OtherError'
else:
if content.status_code == 200 and content.json():
return content.json()
else:
return ''
ErrorList = ['TimeoutError', 'ConnectionError', 'HTTPError', 'TooManyRedirects', 'OtherError']
使用方法:
get_weather('城市名稱')
得到的數據類型為字典,取數據方法簡單示例如下:
demo = get_weather('長沙')
if demo in ErrorList:
print(demo)
else:
test = demo.get("result")
# 獲取城市
city = test.get('city')
# 獲取天氣
weather = test.get('weather')
# 獲取氣溫
temp = test.get('temp')
print(city, weather, temp)
天氣預報查詢接口返回參數:
天氣預報查詢接口返回參數
教程結束!
在使用這個API后,我又購買了另外一個接口,發現使用方法差別不大,所以這篇教程有點通用教程的意思。
下面是問題:
我調用了一個方法,在HTML加載完畢后執行div中出現字符串:
$('.weather-detailed').leoweather({format: '{天氣}'
$('.weather-detailed').text(C);
但是我直接
var C = $('.weather-detailed').leoweather({
format: '{天氣}'
});
或者
var D = $('.weather-detailed').leoweather({format: '{天氣}'
$('.weather-detailed').text(D);
var C = $('.weather-detailed').text()
都只能得到一個對象,我搜索了很久,始終無法解決,我該如何得到執行后的它呢?