如何通过NewsAPI获取前100条新闻标题而非仅第一条?
解决方法
你之前的问题出在:content['articles'][0:100]返回的是一个包含最多100篇文章对象的列表,不是单篇文章,所以不能直接用['title']访问。要输出前100条标题,得遍历这个列表,逐个取出每篇文章的标题。
下面是修改后的完整代码:
import requests # 发送请求 r = requests.get("https://newsapi.org/v2/everything?qInTitle=bangladesh&from=2023-07-17&to=2023-08-16&sortBy=popularity&language=en&apiKey=45c28deca60947fd9ec4d8db2b2c4a81") # 检查请求是否成功 if r.status_code != 200: print(f"请求失败,状态码:{r.status_code}") else: content = r.json() # 确保返回结果里有articles字段 if 'articles' not in content: print("返回结果中没有找到文章数据") else: # 获取前100篇文章(如果返回的文章不足100,就取全部) top_articles = content['articles'][:100] # 遍历并打印每篇文章的标题 for idx, article in enumerate(top_articles, start=1): # 确保当前文章有title字段 if 'title' in article: print(f"{idx}. {article['title']}") else: print(f"{idx}. 无标题")
补充说明:
- 用
content['articles'][:100]替代[0:100]是Python更简洁的写法,而且会自动处理返回文章不足100篇的情况,不会报错 - 加入
enumerate是为了给每条标题加上序号,方便你直观看到条数 - 增加请求状态和字段存在性检查,避免因为API返回异常导致程序直接崩溃
内容的提问来源于stack exchange,提问作者Tyrannical
相关产品推荐
相关产品推荐

