警告
2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅必应搜索 API 文档。 关于为必应搜索创建新的 Azure 资源的说明,请参阅通过 Azure 市场创建必应搜索资源。
使用本快速入门开始使用适用于 C# 的必应新闻搜索客户端库搜索新闻。 虽然必应新闻搜索具有与大多数编程语言兼容的 REST API,但客户端库提供了将服务集成到应用程序中的简单方法。 可以在 GitHub 上找到此示例的源代码。
先决条件
Json.NET 框架,可用作 NuGet 包。
如果使用的是 Linux/MacOS,则可使用 Mono 运行此应用程序。
必应新闻搜索 SDK NuGet 包。 安装此包还会安装以下内容:
- Microsoft.Rest.ClientRuntime(微软.Rest.客户端运行时)
- Microsoft.Rest.ClientRuntime.Azure
- Newtonsoft.Json
若要使用必应新闻搜索客户端库设置控制台应用程序,请浏览到 Manage NuGet Packages
Visual Studio 中解决方案资源管理器中的选项。 添加 Microsoft.Azure.CognitiveServices.Search.NewsSearch
程序包。
创建 Azure 资源
通过创建以下 Azure 资源之一开始使用必应新闻搜索 API:
- 在删除资源前,可通过 Azure 门户使用。
- 使用免费定价层试用该服务,稍后升级到生产付费层。
- 在删除资源前,可通过 Azure 门户使用。
- 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。
创建和初始化项目
在 Visual Studio 中创建新的 C# 控制台解决方案。 然后将以下内容添加到主代码文件中。
using System; using System.Linq; using Microsoft.Azure.CognitiveServices.Search.NewsSearch;
为 API 密钥、搜索词创建变量,然后使用该变量实例化新闻搜索客户端。
var key = "YOUR-ACCESS-KEY"; var searchTerm = "Quantum Computing"; var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(key));
发送请求并分析结果
使用客户端向必应新闻搜索服务发送搜索请求:
var newsResults = client.News.SearchAsync(query: searchTerm, market: "en-us", count: 10).Result;
如果返回了任何结果,请对其进行分析:
if (newsResults.Value.Count > 0) { var firstNewsResult = newsResults.Value[0]; Console.WriteLine($"TotalEstimatedMatches value: {newsResults.TotalEstimatedMatches}"); Console.WriteLine($"News result count: {newsResults.Value.Count}"); Console.WriteLine($"First news name: {firstNewsResult.Name}"); Console.WriteLine($"First news url: {firstNewsResult.Url}"); Console.WriteLine($"First news description: {firstNewsResult.Description}"); Console.WriteLine($"First news published time: {firstNewsResult.DatePublished}"); Console.WriteLine($"First news provider: {firstNewsResult.Provider[0].Name}"); } else { Console.WriteLine("Couldn't find news results!"); } Console.WriteLine("Enter any key to exit..."); Console.ReadKey();
后续步骤
使用此快速入门开始使用适用于 Java 的必应新闻搜索客户端库搜索新闻。 虽然必应新闻搜索具有与大多数编程语言兼容的 REST API,但客户端库提供了将服务集成到应用程序中的简单方法。 可以在 GitHub 上找到此示例的源代码。
先决条件
使用 Maven、Gradle 或其他依赖项管理系统安装必应新闻搜索客户端库依赖项。 Maven POM 文件需要以下声明:
<dependencies>
<dependency>
<groupId>com.microsoft.azure.cognitiveservices</groupId>
<artifactId>azure-cognitiveservices-newssearch</artifactId>
<version>0.0.1-beta-SNAPSHOT</version>
</dependency>
</dependencies>
创建 Azure 资源
通过创建以下 Azure 资源之一开始使用必应新闻搜索 API:
- 在删除资源前,可通过 Azure 门户使用。
- 使用免费定价层试用该服务,稍后升级到生产付费层。
- 在删除资源前,可通过 Azure 门户使用。
- 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。
创建和初始化项目
在偏好的 IDE 或编辑器中创建新的 Java 项目,并导入以下库。
import com.microsoft.azure.cognitiveservices.newssearch.*;
import com.microsoft.azure.cognitiveservices.newssearch.implementation.NewsInner;
import com.microsoft.azure.cognitiveservices.newssearch.implementation.NewsSearchAPIImpl;
import com.microsoft.azure.cognitiveservices.newssearch.implementation.TrendingTopicsInner;
import com.microsoft.rest.credentials.ServiceClientCredentials;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
创建搜索客户端并存储凭据
创建一个名为
getClient()
的方法,该方法返回一个新的NewsSearchAPIImpl
搜索客户端。 将您的终结点作为第一个参数添加到新的NewsSearchAPIImpl
对象中,并创建一个新的ServiceClientCredentials
对象以存储您的凭据。public static NewsSearchAPIImpl getClient(final String subscriptionKey) { return new NewsSearchAPIImpl("https://api.cognitive.microsoft.com/bing/v7.0/", new ServiceClientCredentials() { }); }
若要创建
ServiceClientCredentials
对象,请重写applyCredentialsFilter()
函数。 将OkHttpClient.Builder
作为参数传递给方法,并使用生成器的addNetworkInterceptor()
方法为客户端库调用创建凭据。new ServiceClientCredentials() { @Override public void applyCredentialsFilter(OkHttpClient.Builder builder) { builder.addNetworkInterceptor( new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = null; Request original = chain.request(); // Request customization: add request headers. Request.Builder requestBuilder = original.newBuilder() .addHeader("Ocp-Apim-Subscription-Key", subscriptionKey); request = requestBuilder.build(); return chain.proceed(request); } }); } });
发送和接收搜索请求
创建一个方法,用于调用
getClient()
并发送搜索请求到必应新闻搜索服务。 使用 市场 和 计数 参数筛选搜索,然后打印有关第一个新闻结果的信息:名称、URL、发布日期、说明、提供商名称和搜索的估计匹配总数。public static void newsSearch(String subscriptionKey) { NewsSearchAPIImpl client = getClient(subscriptionKey); String searchTerm = "Quantum Computing"; NewsInner newsResults = client.searchs().list(searchTerm, null, null, null, null, null, 100, null, "en-us", null, null, null, null, null, null, null); if (newsResults.value().size() > 0) { NewsArticle firstNewsResult = newsResults.value().get(0); System.out.println(String.format("TotalEstimatedMatches value: %d", newsResults.totalEstimatedMatches())); System.out.println(String.format("News result count: %d", newsResults.value().size())); System.out.println(String.format("First news name: %s", firstNewsResult.name())); System.out.println(String.format("First news url: %s", firstNewsResult.url())); System.out.println(String.format("First news description: %s", firstNewsResult.description())); System.out.println(String.format("First news published time: %s", firstNewsResult.datePublished())); System.out.println(String.format("First news provider: %s", firstNewsResult.provider().get(0).name())); } else { System.out.println("Couldn't find news results!"); } }
将您的搜索方法添加到
main()
方法中以执行代码。public static void main(String[] args) { String subscriptionKey = "YOUR-SUBSCRIPTION-KEY"; NewsSearchSDK.newsSearch(subscriptionKey); }
后续步骤
使用此快速入门开始使用适用于 JavaScript 的必应新闻搜索客户端库搜索新闻。 虽然必应新闻搜索具有与大多数编程语言兼容的 REST API,但客户端库提供了将服务集成到应用程序中的简单方法。 可以在 GitHub 上找到此示例的源代码。
先决条件
- 最新版本的 Node.js。
-
适用于 JavaScript 的必应新闻搜索 SDK
- 若要安装,请运行
npm install @azure/cognitiveservices-newssearch
- 若要安装,请运行
- 用于认证客户端的
CognitiveServicesCredentials
包中的@azure/ms-rest-azure-js
类。- 若要安装,请运行
npm install @azure/ms-rest-azure-js
- 若要安装,请运行
创建 Azure 资源
通过创建以下 Azure 资源之一开始使用必应新闻搜索 API:
- 在删除资源前,可通过 Azure 门户使用。
- 使用免费定价层试用该服务,稍后升级到生产付费层。
- 在删除资源前,可通过 Azure 门户使用。
- 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。
创建和初始化应用程序
创建
CognitiveServicesCredentials
的实例。 为订阅密钥和搜索词创建变量。const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials; let credentials = new CognitiveServicesCredentials('YOUR-ACCESS-KEY'); let search_term = 'Winter Olympics'
实例化客户端:
const NewsSearchAPIClient = require('@azure/cognitiveservices-newssearch'); let client = new NewsSearchAPIClient(credentials);
发送搜索查询
使用客户端通过查询词进行搜索,在本例中为“冬季奥运会”:
client.newsOperations.search(search_term).then((result) => { console.log(result.value); }).catch((err) => { throw err; });
代码将内容打印到控制台,而无需解析任何文本。 结果(如果每个类别有)将包括:
_type: 'NewsArticle'
_type: 'WebPage'
_type: 'VideoObject'
_type: 'ImageObject'
后续步骤
使用本快速入门开始使用适用于 Python 的必应新闻搜索客户端库搜索新闻。 虽然必应新闻搜索具有与大多数编程语言兼容的 REST API,但客户端库提供了将服务集成到应用程序中的简单方法。 可以在 GitHub 上找到此示例的源代码。
先决条件
- Python 2.x 或 3.x
建议使用 虚拟环境 进行 Python 开发。 可以使用 venv 模块安装和初始化虚拟环境。 必须安装适用于 Python 2.7 的 virtualenv。 可以使用以下项创建虚拟环境:
python -m venv mytestenv
可以使用以下命令安装必应新闻搜索客户端库依赖项:
python -m pip install azure-cognitiveservices-search-newssearch
创建 Azure 资源
通过创建以下 Azure 资源之一开始使用必应新闻搜索 API:
- 在删除资源前,可通过 Azure 门户使用。
- 使用免费定价层试用该服务,稍后升级到生产付费层。
- 在删除资源前,可通过 Azure 门户使用。
- 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。
创建和初始化应用程序
在偏好的 IDE 或编辑器中创建新的 Python 文件,并导入以下库。 为订阅密钥和搜索词创建变量。
from azure.cognitiveservices.search.newssearch import NewsSearchClient from msrest.authentication import CognitiveServicesCredentials subscription_key = "YOUR-SUBSCRIPTION-KEY" endpoint = "YOUR-ENDPOINT" search_term = "Quantum Computing"
初始化客户端并发送请求
创建
CognitiveServicesCredentials
实例。client = NewsSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
将搜索查询发送到新闻搜索 API,存储响应。
news_result = client.news.search(query=search_term, market="en-us", count=10)
分析响应
如果找到任何搜索结果,请打印第一个网页结果:
if news_result.value:
first_news_result = news_result.value[0]
print("Total estimated matches value: {}".format(
news_result.total_estimated_matches))
print("News result count: {}".format(len(news_result.value)))
print("First news name: {}".format(first_news_result.name))
print("First news url: {}".format(first_news_result.url))
print("First news description: {}".format(first_news_result.description))
print("First published time: {}".format(first_news_result.date_published))
print("First news provider: {}".format(first_news_result.provider[0].name))
else:
print("Didn't see any news result data..")