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

如何使用新闻搜索API仅获取英国地区的新闻结果?

解决方法

关键参数修正

你的代码里有两个参数错误,导致无法严格限制新闻仅来自英国:

  • cc参数格式错误:cc要求传入ISO 3166-1 alpha-2国家代码(英国对应GB),你之前用的en-GB是mkt参数的格式,不符合cc的要求。
  • sortBy参数值错误:sortBy的有效值只有"Date"或"Relevance",你传入了具体日期字符串,这会导致参数无效,API可能忽略该参数,进而影响地区限制规则的生效。

修改后的完整代码

import datetime
import requests
import json

search_term = "flood, fire, storm"
search_url = "https://api.bing.microsoft.com/v7.0/news/search"

headers = {"Ocp-Apim-Subscription-Key" : subscription_key}
params  = {
    "q": search_term,
    "cc": "GB",  # 英国的标准国家代码
    "mkt": "en-GB",  # 英文-英国市场
    "textDecorations": True,
    "setLang": "en-gb",
    "textFormat": "HTML",
    "sortBy": "Date"  # 正确的排序参数值
}

response = requests.get(search_url, headers=headers, params=params)
response.raise_for_status()
search_results = json.dumps(response.json(), indent=2)

print(search_results)

二次过滤(可选)

如果API仍返回少量非英国来源的结果,可以在解析数据时手动筛选,比如检查新闻来源的国家标识:

data = response.json()
uk_only_news = [item for item in data["value"] 
                if item.get("country") == "GB" 
                or "United Kingdom" in item["provider"][0]["name"]]
print(json.dumps(uk_only_news, indent=2))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:35:49