请求:“params”关键字无法正常工作?

问题描述 投票:0回答:1

我正在尝试使用“params”关键字向GitHub API发出请求:

import requests

parameters = {'language': 'python', 'sort': 'stars'}

url = 'https://api.github.com/search/repositories' #?language:python&sort=stars

response = requests.get(url, params=parameters) 
print(response.url)
response_dict = response.json()

items_list = response_dict['items']

for item in items_list:
    print(item['name'])

我收到以下错误:

Traceback (most recent call last):
  File "github.py", line 10, in <module>
    items_list = response_dict['items']
KeyError: 'items'

但是,如果我跳过params方法并将整个URL分配给变量,那么相同的代码工作正常。通过打印两个方法的URL,我注意到使用“params”省略了URL中的“q =”部分。可能是错误的原因,如果是这样,我该如何解决?

python github python-requests
1个回答
0
投票

有关Search API的文档声明,您可以在查询字符串参数language中指定包含由:分隔的q的字段,如下所示:

import requests

parameters = {"q": "language:python", "sort": "stars"}
url = "https://api.github.com/search/repositories"

response = requests.get(url, params=parameters)
response.raise_for_status()
response_dict = response.json()

for item in response_dict["items"]:
    print(item["name"])

你可以查看documentation,了解你可以添加到q的其他内容。

© www.soinside.com 2019 - 2024. All rights reserved.