首页 > 解决方案 > 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)

当我打印结果而不是获取华尔街日报时,我会从所有来源获取新闻。

标签: pythonpython-requests

解决方案


您需要在查询中实际使用源,并且也可以通过这种方式传递 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']

推荐阅读