我正在尝试通过连接到天气API来学习请求和练习。但由于某种原因,我不能让它工作?很明显,天气API以某种方式想要参数,我似乎无法弄清楚它是如何转化为请求的。
这是我的代码:
TypeError: request() got an unexpected keyword argument 'q'
以下是API页面的链接: https://openweathermap.org/current
我看到天气页面需要q = city的参数,但我得到的错误是:
{{1}}
此处还有我所指的“请求”页面:http://docs.python-requests.org/en/master/
感谢您的帮助!
答案 0 :(得分:1)
请查看requests
用户手册,至少quickstart guide。
您要使用的RESTful API需要带有q="City Name"
参数的GET请求。此外,您必须拥有appid并为每个请求添加它。
q="City Name"
和APPID=xxx
参数以下是相应的要求:
api_url = 'http://api.openweathermap.org/data/2.5/weather'
appid = ...
r = requests.get(url=api_url, params=dict(q='Anderson', APPID=appid))
答案 1 :(得分:0)
尝试将您的呼叫更改为后续呼叫(通过将api密钥添加到params
):
r = requests.get('http://api.openweathermap.org/data/2.5/weather', params={'q': 'Anderson', 'APPID': YOUR_API_KEY})
答案 2 :(得分:0)
openweather需要appid
,个人使用免费(https://openweathermap.org/appid#get)
>>> import requests
>>> r = requests.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1')
>>> loc_weather = r.content.strip()
>>> loc_weather
'{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}'
答案 3 :(得分:0)
这适用于 Weatherbit。
网址:
url = "https://api.weatherbit.io/v2.0/history/daily"
创建负载:
payload = {'key':'12345fcfa0hjde13a7896fbdae1ghjkjh',
'city_id': '1261481', # This is New Delhi
'start_date': '2021-03-13',
'end_date': '2021-03-14'}
使用 GET 调用(网站指定支持 GET 调用):
data = requests.get(url, params=payload)
assert data.status_code == 200
assert 'error' not in data.json().keys()
您的数据:
data.json() # Or text or content
我的系统规格:Python 3.8,请求 2.25.1