python爬取天气信息

版权声明: https://blog.csdn.net/lhhnb/article/details/86475927

功能讲解:

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()

猜你喜欢

转载自blog.csdn.net/lhhnb/article/details/86475927