python - python函数获取新闻源的问题-请求包
问题描述
我在 python 中创建了一个函数来从我特别请求的来源获取新闻。但是,当我运行该函数时,它会带来所有源而不是我请求的源。
这是我到目前为止的代码:
import requests
import json
apiKey = "4f7c31f7d0084161bffec9b5d4f78e33"
def getNews(source):
# news api
url = "http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=4f7c31f7d0084161bffec9b5d4f78e33"
r = requests.get(url)
data = r.json()
# read the url articles requested
urls = []
for a in data["articles"]:
urls.append(a["url"])
return urls
if __name__ == '__main__':
results = getNews('the-wall-street-journal')
print(results)
当我打印结果而不是获取华尔街日报时,我会从所有来源获取新闻。
解决方案
您需要在查询中实际使用源,并且也可以通过这种方式传递 api 密钥。我还必须修改源以获得结果。
import requests
import json
apiKey = "redacted!"
def getNews(source, key):
# news api
url = f"http://newsapi.org/v2/top-headlines?q={source}&country=us&category=business&apiKey={key}"
r = requests.get(url)
data = r.json()
# read the url articles requested
urls = []
for a in data["articles"]:
urls.append(a["url"])
return urls
if __name__ == '__main__':
results = getNews('wall street journal', apiKey)
print(results)
输出
['https://www.wsj.com/articles/bonds-were-a-safety-net-when-stocks-fell-investors-fret-they-arent-anymore-11601887725', 'https://www.wsj.com/articles/what-you-need-to-know-about-social-impact-investing-11601823600']
推荐阅读
- php - 如何从 Facebook 个人资料中获取属性?
- r - 在数据框中进行特定排序后,如何接收带有列名的向量
- c - 关于除法和模数的 C 程序介绍性编程的问题
- php - 根据 Woocommerce 中的客户总购买金额添加百分比折扣
- summernote - 如何在 Summernote 中插入文本(不是节点)并将光标移回 X 个字符?
- node.js - Node Express Mocha 测试:TypeError: chai.request is not a function
- python - 如何处理我的 AWS EC2 实例上的多个 Python 请求?
- php - 点击后通知图标隐藏号码
- python - 在 Python 3.6+ 中按值排序字典
- firebase - 如何在无服务器模型中初始化 firebase 应用程序?什么是并发应用程序限制?