获取IP对应地点和天气状态
天气:采用心知天气免费API获取天气信息,https://seniverse.yuque.com/hyper_data/api_v3/nyiu3t
import requests
import timedef get_location_by_ip ( ip_address) : url = f"http://ipinfo.io/ { ip_address} /json" response = requests. get( url) if response. status_code == 200 : data = response. json( ) print ( data) city = data. get( 'city' , None ) return cityelse : print ( f"地点请求失败,状态码: { response. status_code} " ) return None def get_weather ( api_key, location) : base_url = "https://api.seniverse.com/v3/weather/now.json" params = { 'key' : api_key, 'location' : location, 'language' : 'zh-Hans' , 'unit' : 'c' } st = time. time( ) response = requests. get( base_url, params= params) if response. status_code == 200 : data = response. json( ) if data[ 'results' ] : result = data[ 'results' ] [ 0 ] now = result[ 'now' ] city = result[ 'location' ] [ 'name' ] print ( f"result: { result} " ) print ( f"城市: { city} " ) print ( f"天气: { now[ 'text' ] } " ) print ( f"温度: { now[ 'temperature' ] } °C" ) else : print ( "没有找到天气数据" ) else : print ( f"天气请求失败,状态码: { response. status_code} " ) print ( f"耗时: { time. time( ) - st} s" )
def main ( ) : api_key = 'xxxxxx' ip = "xxxxxx" location = get_location_by_ip( ip) print ( f"IP地址 { ip} 对应的地理位置是: { location} " ) if location: get_weather( api_key, location) if __name__ == "__main__" : main( )