python调用百度接口,获取天气信息
需要到百度注册开发者账号,通过账号获取到每个账号私有的应用访问(AK)
使用此脚本还需要district_id.csv文档,在我资源中可以免费下载,也可在百度天气API接口文档处下载进行下载。
# -*- coding: utf-8 -*-
# author: herman_tang
import requests
import re
import json
import csv
import sys
import os
APIkey = 'eiaOYEz8eO9MpU3wKaz0WDA64xaGu2FU'
city = input("请输入要查询的城市名: ")
file1 = r'E:\python文件\tang01\district_id.csv'
def is_chinese():
count1 = len(city)
count =0
while count < count1:
if '\u4e00' <= city[count] <= '\u9fff':
number = 'True'
else:
number = 'False'
break
count += 1
return number
def distr_id():
with open(file1, 'r', encoding='utf-8') as filea:
lines = csv.reader(filea)
for i in lines:
if i[5] == city:
district_id = i[1]
return district_id
def get_info(data_type: str ='all'):
"""
这里传递的产生来data_type一共以下几种类型:
1、all 所有信息
2、now 实时数据
3、alert 气象预警
4、index 生活指数
5、fc 预报数据
6、fc_hour 未来24小时小时预报(高级字段)
默认为all,返回所有的信息
"""
try:
district_id = distr_id()
except:
return "您输入的城市名{}不正确,请重新输入..........".format(city)
url = "http://api.map.baidu.com/weather/v1/?district_id={}&data_type={}&output=json&ak={}".format(district_id, data_type, APIkey)
payload = {}
headers = {
'Cookie': 'BAIDUID=F47B1A43BB52CB5876036267ABD4EEC7:FG=1',
"Content-Type": "application/json"
}
response = requests.request("GET", url, headers=headers, data = payload)
info = json.dumps(json.loads(response.text), ensure_ascii=False)
weather_info = eval(info)
return weather_info
def P_info():
'''
这里是调用get_info函数,解析获取到的信息,将信息进行转换
'''
weather_info = get_info()['result']
now = weather_info['now']
futrue = weather_info['forecasts']
country = weather_info['location']['country']
province = weather_info['location']['province']
city = weather_info['location']['city']
county = weather_info['location']['name']
text = now['text']
temp = now['temp']
feels_like = now['feels_like']
rh = now['rh']
wind_class = now['wind_class']
wind_dir = now['wind_dir']
#now = '实时数据:'
'''
这里是获取当天天气信息
'''
if county == city[:-1]:
print ('您要查询天气的位置为: {}{}{}市'.format(country, province, county))
else:
print ('您要查询天气的位置为: {}{}{}{}市'.format(country, province, city, county))
text_info = ['当前天气为:{}'.format(text),'当前为气温: {}摄氏度'.format(temp), '当前湿度为: {}'.format(rh), '当前体感温度为: {}'.format(feels_like),
'当前风向为: {}'.format(wind_dir), '当前风力为: {}级'.format(wind_class)]
for i in text_info:
print (i)
"""
下面是解析未来几天的天气信息
"""
for i in futrue:
text_day = i['text_day']
text_night = i['text_night']
high = i['high']
low = i['low']
wc_day = i['wc_day']
wd_day = i['wd_day']
wc_night = i['wc_night']
wd_night = i['wd_night']
date = i['date']
week = i['week']
futrue_info = ['日期:{}'.format(date), week, '白天天气: {}'.format(text_day), '晚上天气: {}'.format(text_night), '最高气温: {}摄氏度'.format(high),
'最低气温: {}摄氏度'.format(low), '白天风力: {}'.format(wc_day), '白天风向: {}'.format(wd_day), '晚上风力: {}'.format(wc_night), '晚上风向: {}'.format(wd_night)]
for i in futrue_info:
print (i)
return "我喜欢紧紧抱住你的那一刻,就像得到了全世界!"
def select():
zh = is_chinese()
if zh == 'True':
try:
return P_info()
except:
return "NameError: 您输入的城市名字有误......."
else:
return 'NaMeError: 请输入中文名.............'
if __name__ == "__main__":
s1 =select()
print (s1)
#P_info()