如何用API Key查询《卫报》含关键词文章数?Python代码报错求助
《卫报》API文章数量查询代码报错排查方案
你的代码主要有三个问题导致报错,逐一修正即可:
API请求URL错误
原URL中的/#/search是《卫报》API文档网页的前端路由,实际API接口路径应为/search,需要去掉/#/部分,否则请求会返回错误的JSON结构。日期参数名称与格式不匹配
《卫报》API的日期范围参数是from-date和to-date,而非你沿用的《纽约时报》的begin_date和end_date;同时它要求日期格式为YYYY-MM-DD,原代码的YYYYMMDD格式会被识别为无效日期,双重不匹配会导致API无法正确处理请求。返回结构字段错误
《卫报》API中文章总数的字段是response.total,而非你写的response.meta.hits,这是触发KeyError的直接原因。
修正后的代码:
# Checking number of articles on a topic in The Guardian import requests def number_of_articles(api_key, keyword, begin_date="1980-01-01", end_date="2024-01-01"): # 修正URL路径、参数名和日期格式 url_query = f"http://content.guardianapis.com/search?q={keyword}&from-date={begin_date}&to-date={end_date}&api-key={api_key}" print(url_query) res = requests.get(url_query) # 校验请求是否成功 if res.status_code != 200: print(f"请求失败,状态码:{res.status_code}") return None json_res = res.json() # 检查API是否返回错误信息 if 'error' in json_res: print(f"API错误:{json_res['error']}") return None # 正确获取文章总数 hits = json_res["response"]["total"] return hits # 确保guardian_api_key已提前正确定义 print(number_of_articles(api_key=guardian_api_key, keyword="vote"))
内容的提问来源于stack exchange,提问作者RebecaOdC
相关产品推荐
相关产品推荐

