快速入门:使用必应新闻搜索客户端库
警告
2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅必应搜索 API 文档。 关于为必应搜索创建新的 Azure 资源的说明,请参阅通过 Azure 市场创建必应搜索资源。
通过本快速入门开始使用适用于 C# 的必应新闻搜索客户端库来搜索新闻。 虽然必应新闻搜索具有与大多数编程语言兼容的 REST API,但该客户端库提供了一种简单方法来将服务集成到应用程序中。 可以在 GitHub 上找到此示例的源代码。
任何版本的 Visual Studio 2017 或更高版本。
Json.NET 框架,可以 NuGet 包的形式提供。
如果使用的是 Linux/MacOS,则可使用 Mono 运行此应用程序。
必应新闻搜索 SDK NuGet 程序包。 安装此程序包还会安装以下项:
- Microsoft.Rest.ClientRuntime
- Microsoft.Rest.ClientRuntime.Azure
- Newtonsoft.Json
若要使用必应新闻搜索客户端库设置控制台应用程序,请浏览到 Visual Studio 中的解决方案资源管理器中的“Manage NuGet Packages
”选项。 添加 Microsoft.Azure.CognitiveServices.Search.NewsSearch
程序包。
通过创建以下 Azure 资源之一开始使用必应新闻搜索 API:
- 在删除资源前,可通过 Azure 门户使用。
- 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
- 在删除资源前,可通过 Azure 门户使用。
- 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。
在 Visual Studio 中创建一个新的 C# 控制台解决方案。 然后将以下内容添加到主代码文件。
C#using System; using System.Linq; using Microsoft.Azure.CognitiveServices.Search.NewsSearch;
为 API 密钥、搜索词创建变量,然后使用它实例化新闻搜索客户端。
C#var key = "YOUR-ACCESS-KEY"; var searchTerm = "Quantum Computing"; var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(key));
使用客户端向必应新闻搜索服务发送搜索请求:
C#var newsResults = client.News.SearchAsync(query: searchTerm, market: "en-us", count: 10).Result;
如果返回了任何结果,则对其进行分析:
C#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 资源之一开始使用必应新闻搜索 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
对象来存储凭据。Javapublic static NewsSearchAPIImpl getClient(final String subscriptionKey) { return new NewsSearchAPIImpl("https://api.cognitive.microsoft.com/bing/v7.0/", new ServiceClientCredentials() { }); }
若要创建
ServiceClientCredentials
对象,请替代applyCredentialsFilter()
函数。 将OkHttpClient.Builder
传递到该方法,并使用 builder 的addNetworkInterceptor()
方法创建用于客户端库调用的凭据。Javanew 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()
并向必应新闻搜索服务发送一个搜索请求。 使用 market 和 count 参数对搜索进行筛选,然后输出第一个新闻结果的信息:名称、URL、发布日期、说明、提供者名称以及你的搜索的估计匹配项总数。Javapublic 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()
方法来执行代码。Javapublic 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
- 若要安装,请运行
-
@azure/ms-rest-azure-js
包中的CognitiveServicesCredentials
类,用于对客户端进行身份验证。- 若要安装,请运行
npm install @azure/ms-rest-azure-js
- 若要安装,请运行
通过创建以下 Azure 资源之一开始使用必应新闻搜索 API:
- 在删除资源前,可通过 Azure 门户使用。
- 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
- 在删除资源前,可通过 Azure 门户使用。
- 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。
创建
CognitiveServicesCredentials
的实例: 为订阅密钥和搜索词创建变量。JavaScriptconst CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials; let credentials = new CognitiveServicesCredentials('YOUR-ACCESS-KEY'); let search_term = 'Winter Olympics'
对客户端进行实例化:
JavaScriptconst NewsSearchAPIClient = require('@azure/cognitiveservices-newssearch'); let client = new NewsSearchAPIClient(credentials);
使用客户端通过查询词进行搜索,在本例中查询词为“Winter Olympics”:
JavaScriptclient.newsOperations.search(search_term).then((result) => { console.log(result.value); }).catch((err) => { throw err; });
代码会将 result.value
项输出至控制台,并且不会分析任何文本。 结果(如果每个类别都有结果)将包括:
_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 资源之一开始使用必应新闻搜索 API:
- 在删除资源前,可通过 Azure 门户使用。
- 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
- 在删除资源前,可通过 Azure 门户使用。
- 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。
在你最喜欢使用的 IDE 或编辑器中新建一个 Python 文件,并导入以下库。 为订阅密钥和搜索词创建变量。
Pythonfrom azure.cognitiveservices.search.newssearch import NewsSearchClient from msrest.authentication import CognitiveServicesCredentials subscription_key = "YOUR-SUBSCRIPTION-KEY" endpoint = "YOUR-ENDPOINT" search_term = "Quantum Computing"
创建
CognitiveServicesCredentials
的实例。Pythonclient = NewsSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
向新闻搜索 API 发送搜索查询并存储响应。
Pythonnews_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..")