python爬取天氣資訊
阿新 • • 發佈:2019-01-14
功能講解:
1.根據你的ip地址,定位你所在的城市,然後把城市引數傳給city_weather函式,向伺服器傳送請求,得到天氣結果
2.直接輸入你要查詢的城市名,就可獲取天氣情況。
程式碼:
import requests,json
def city_weather(city_name):
request=requests.get('http://api.map.baidu.com/telematics/v3/weather?location={}&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?' .format(city_name)) # 向網站傳送Get請求,返回的是請求狀態,可以判斷請求是否成功
print(request)
print(request.text)
json_str=request.text # 返回的是請求狀態和要解析的json字串
json_dict=json.loads(json_str) # 把json字串轉化為字典
data_dict=json_dict['results']
result=data_dict[0]
city=result['currentCity']
pm=result[ 'pm25']
index=result['index']
weather=result['weather_data']
print('city: {} pm: {}'.format(city,pm))
for it in index:
des=it['des']
title=it['title']
zs=it['zs']
print('建議: {} {}:{}'.format(des,title,zs))
for it in weather:
date=it['date' ]
temperature = it['temperature']
weather = it['weather']
wind = it['wind']
print('日期: {} 溫度:{} 天氣: {} 風力: {}'.format(date,temperature,weather,wind))
# 根據ip定位你的位置
def city_ip(url='https://api.map.baidu.com/location/ip?ak=KHkVjtmfrM6NuzqxEALj0p8i1cUQot6Z'):
request=requests.get(url)
print(request)
json_str=request.text
json_dict=json.loads(json_str)
data_dict=json_dict['content']
return data_dict['address_detail']['city']
def main():
while True:
print("""
1.根據ip地址定位所在位置天氣:
2.根據輸入城市名稱查詢天氣:
""")
n=input('輸入運算元:')
while n!='1' and n!='2':
n = input('重新輸入運算元:')
if n=='1':
city_weather(city_ip())
elif n=='2':
name=input('城市名稱:')
city_weather(name)
main()