试图在天气api上使用GET,但python不断添加问号

时间:2016-09-01 11:04:14

标签: python api request

所以我想用天气api尝试一些东西,但我似乎无法让它工作。当我运行代码时,Python解释器不断向我的请求添加一个问号,所以我得到一个404响应,没有找到。

这是我的代码:

import requests
from requests.auth import HTTPDigestAuth
import json
url = "http://opendata-download-metfcst.smhi.se"

myResponse = requests.get(url,"api/category/pmp2g/version/2/geotype/point/lon/16.158/lat/58.5812/data.json", verify=True)

if(myResponse.ok):
    jData = json.loads(myResponse.content)
    print("The response contains {0} properties".format(len(jData)))
    print("\n")
    for key in jData:
        print (key + " : " + jData[key])
else:
     myResponse.raise_for_status()

这是我的错误信息:

requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://opendata-download-metfcst.smhi.se/?/category/pmp2g/version/2/geotype/point/lon/16.158/lat/58.5812/data.json

正如您所看到的,它用问号替换了请求“api”的开头。这就是它无法找到资源的原因。为什么这样做?

1 个答案:

答案 0 :(得分:0)

尝试使用:

myResponse = requests.get("{}/api/category/pmp2g/version/2/geotype/point/lon/16.158/lat/58.5812/data.json".format(url))

目前,您将其余的URL作为GET参数传递。

来自requests文档:

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('http://httpbin.org/get', params=payload)

通过打印网址,您可以看到网址已正确编码:

>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1