python - 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 类型 - 所以这可能是错误的,看起来它可能是正确的,但我不确定。
如果还有其他人需要,请告诉我。
感谢您的任何帮助。
解决方案
推荐阅读
- python - 我可以设置 modin 的并行 read_sql 函数的隔离级别吗?
- javascript - 防止方法发布表单刷新
- mysql - 由于多个加载器导致的 MySQL 大表碎片
- python - Prolog编程从python代码转换
- python - netCDF4 填充值行为
- c++ - 提取矩阵的对角线
- javascript - 我们如何能够在 Node.js 中使用 import 语法 (es6) 和 require (commonjs) 来导入 express 等第三方包?
- next.js - 根据 Next.js next.config.js 中的标头或 cookie 进行重定向
- reactjs - 材质 UI 无法与 Next.js 一起正常工作
- nuxt.js - asyncData 不显示 API 结果