You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的NewsApi获取精准的商业与科技类头条新闻?

问题分析与解决方案

原代码的核心问题

  • 分页参数错误:get_top_headlines的page设为30,远超头条内容实际分页范围(头条总量极少,通常page从1开始,page_size最大为100),直接导致无结果返回。
  • Sources参数用法错误:NewsApiClient.get_sources()返回的是源信息字典列表,而get_top_headlines的sources需要逗号分隔的源ID字符串;同时该方法的category参数仅支持单个类别(如business或technology),不能同时传入多个。
  • API方法选型偏差:get_top_headlines仅聚焦当前最热门头条,针对Blackrock、Apple stock这类特定关键词,命中概率极低,更适合用get_everything并优化筛选条件来获取相关优质内容。

修正后的实现方案

方案1:优化get_top_headlines获取精准热门头条

如果坚持要获取头条类内容,调整分页、修正sources参数,并缩小关键词范围:

from newsapi import NewsApiClient

def get_top_headlines_for_topic(phrase, n_news=15):
    newsapi = NewsApiClient(api_key='YOUR_API_KEY')
    
    # 分别获取商业、科技类英文源ID并合并成字符串
    business_sources = [src['id'] for src in newsapi.get_sources(category='business', language='en')['sources']]
    tech_sources = [src['id'] for src in newsapi.get_sources(category='technology', language='en')['sources']]
    all_sources = ','.join(business_sources + tech_sources)
    
    # 头条仅需第一页,无需设置大页码
    articles = newsapi.get_top_headlines(
        q=phrase,
        language="en",
        page_size=n_news,
        page=1,
        sources=all_sources
    )
    return articles['articles']

# 调用示例
print(get_top_headlines_for_topic('Blackrock'))

方案2:用get_everything获取优质相关内容(推荐)

针对特定关键词,通过精确匹配、权威域名、热度排序和时间范围过滤无关结果:

from newsapi import NewsApiClient

def get_relevant_high_quality_news(phrase, n_news=15):
    newsapi = NewsApiClient(api_key='YOUR_API_KEY')
    
    # 用双引号包裹关键词,强制精确匹配完整短语
    query = f'"{phrase}"'
    
    # 指定权威商业/科技媒体域名,过滤低质量内容
    trusted_domains = 'bloomberg.com,wsj.com,cnn.com,techcrunch.com,reuters.com'
    
    articles = newsapi.get_everything(
        q=query,
        language="en",
        page_size=n_news,
        page=1,
        domains=trusted_domains,
        sort_by='popularity',  # 按热度排序,优先热门内容
        from_param='2024-01-01'  # 限制获取近期内容,提升相关性
    )
    return articles['articles']

# 调用示例
print(get_relevant_high_quality_news('Apple stock'))

额外优化建议

  • 精确匹配关键词:用双引号包裹关键词(如"Apple stock"),避免API拆分关键词导致的无关结果。
  • 缩小时间范围:通过from_param和to_param设置时间窗口,只获取近期内容。
  • 筛选权威源:优先指定知名商业/科技媒体域名,进一步提升内容质量。
  • 合理分页:如需更多内容,逐页递增page参数,但注意API调用次数限制。

内容的提问来源于stack exchange,提问作者Cr3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 13:10:25