http获取python查询密钥值

2024-04-28 17:12:07 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个名为“query_string”的函数,它不接受任何参数。该函数将向url“https://fury.cse.buffalo.edu/ps-api/a”发出HTTPS GET请求,其中包含一个包含键值对x=5、y=4和z=5的查询字符串。服务器的响应将是一个JSON字符串,表示格式为“{”answer“}”的对象,其中是一个浮点数。以浮点形式返回键“answer”处的值

    import urllib.request
    import json

    def query_string():
        response = urllib.request.urlopen("https://fury.cse.buffalo.edu/ps-api/a")
        content_string = response.read().decode()
        content=json.loads(content_string)
        return float(content['answer'])

输出:输入[]上的函数查询字符串不正确

返回值:-1.0 预期:119.99

你知道我怎么解决这个问题吗?在


Tags: 函数字符串answerhttpsimportapistringcontent
2条回答

您可以使用requests包执行类似的操作。它非常有用。您可以在传递给params关键字参数的dict中添加查询参数

def query_string():
    import requests
    url=r'https://fury.cse.buffalo.edu/ps-api/a'
    payload={
    'x':5,
    'y':4,
    'z':5}
    r=requests.get(url,params=payload)
    j=r.json()
    print(j)

为urllib编辑

^{pr2}$
import urllib.request
import json

def query_string():
    url = "https://fury.cse.buffalo.edu/ps-api/a"
    url = url + "?x=5&y=4&z=5"
    response = urllib.request.urlopen(url)
    content_string = response.read().decode()
    content=json.loads(content_string)
    return float(content['answer'])

经过一番研究后终于修好了

相关问题 更多 >