首页 > 解决方案 > Python - 使用 OpenWeatherMap API 问题

问题描述

我目前正在完成一门 Python 课程(第一门课程,所以我是初学者)并且正在编写一个 Python 脚本来提取用户的 IP 地址以查找城市并使用 OpenWeatherMap API 来提取他们当前的天气/温度。

我有一个 API 密钥,但问题是当我启动为获取天气信息而创建的函数时。它说有一个 ValueError: unknown URL type。当我复制 URL 并将其粘贴到 Chrome 中时,我得到了天气信息,所以我对它为什么不起作用感到有点困惑。我一直试图弄清楚这一点,因为我确信这是一个小而容易的错误,但我无法指出。

代码如下:

import urllib
from urllib import request
import json
import re

# Get Public IP Address
def get_ip():
    url = 'http://checkip.dyndns.com/'
    data = request.urlopen(url).read()
    IP = data[-29:-16].decode('utf-8')
    return IP

IP = get_ip()

# Get Location
url = 'http://ipinfo.io/' + IP + '/json'
response = request.urlopen(url)
data = json.load(response)
city = data['city']

# Get Weather
def get_weather(ip_address):
    
    api_key = str('c6cd68a191650e7e4088f67e068f71ce')
    
    response = request.urlopen(f'api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}')
    data = json.load(response)
    
    print("Your City : " + city)
    print("Current Weather : " + str(data['main']['temp'] - 273) + "F")

当我尝试测试运行它时:

get_weather(IP)

我得到值错误:

ValueError: unknown url type: 'api.openweathermap.org/data/2.5/weather?q=Orlando&appid=c6cd68a191650e7e4088f67e068f71ce'

我尝试的主要事情是弄清楚显示“http.client.HTTPResponse”的 url 类型 - 所以这可能是错误的,看起来它可能是正确的,但我不确定。

如果还有其他人需要,请告诉我。

感谢您的任何帮助。

标签: pythonpython-3.xapi

解决方案


推荐阅读