Bing新闻API是Microsoft Cognitive Services提供的一项服务,允许开发者通过RESTful API访问Bing搜索引擎的新闻结果。它能够返回与搜索查询相关的新闻文章,支持多种过滤和排序选项。
import requests
import time
from requests.exceptions import HTTPError
def safe_bing_news_api_call(api_key, query, max_retries=3):
endpoint = "https://api.cognitive.microsoft.com/bing/v7.0/news/search"
headers = {"Ocp-Apim-Subscription-Key": api_key}
params = {"q": query, "count": 50}
for attempt in range(max_retries):
try:
response = requests.get(endpoint, headers=headers, params=params)
response.raise_for_status()
return response.json()
except HTTPError as e:
if e.response.status_code == 429: # 速率限制
retry_after = int(e.response.headers.get('Retry-After', 5))
time.sleep(retry_after)
continue
raise
raise Exception("Max retries exceeded")
// 简单的API使用监控示例
class BingNewsAPIClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.callCount = 0;
this.lastCallTime = 0;
}
async searchNews(query) {
const now = Date.now();
const timeSinceLastCall = now - this.lastCallTime;
// 确保至少200ms间隔
if (timeSinceLastCall < 200) {
await new Promise(resolve =>
setTimeout(resolve, 200 - timeSinceLastCall));
}
try {
const response = await fetch(
`https://api.cognitive.microsoft.com/bing/v7.0/news/search?q=${encodeURIComponent(query)}`,
{ headers: { "Ocp-Apim-Subscription-Key": this.apiKey } }
);
this.callCount++;
this.lastCallTime = Date.now();
if (response.headers.get('X-RateLimit-Remaining') < 10) {
console.warn('API调用接近限制');
}
return await response.json();
} catch (error) {
console.error('API调用失败:', error);
throw error;
}
}
}
通过合理设计调用策略和错误处理机制,可以有效应对Bing新闻API的各种调用限制,确保服务的稳定性和可靠性。
没有搜到相关的沙龙