快速入門:使用 Bing 新聞搜尋用戶端程式庫

警告

在 2020 年 10 月 30 日,Bing 搜尋 API 已從 Azure AI 服務移至 Bing 搜尋 服務。 本文件僅供參考之用。 如需更新的文件,請參閱 Bing 搜尋 API 文件。 如需針對 Bing 搜尋建立新 Azure 資源的指示,請參閱透過 Azure Marketplace 建立 Bing 搜尋資源

使用本快速入門,透過適用於 C# 的 Bing 新聞搜尋用戶端程式庫開始搜尋新聞。 雖然 Bing 新聞搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。

Prerequisites

若要使用 Bing 新聞搜尋用戶端程式庫來設定主控台應用程式,請在 Visual Studio 中瀏覽至 [方案總管] 中的 Manage NuGet Packages 選項。 新增 Microsoft.Azure.CognitiveServices.Search.NewsSearch 套件。

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 新聞搜尋 API:

Bing 搜尋 v7 資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 使用免費定價層來試用服務,之後可升級至付費層以用於實際執行環境。

多服務資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。

建立專案並將其初始化

  1. 在 Visual Studio 中建立新的 C# 主控台解決方案。 然後將下列內容新增至主要程式碼檔案。

    using System;
    using System.Linq;
    using Microsoft.Azure.CognitiveServices.Search.NewsSearch;
    
  2. 為您的 API 金鑰建立變數 (搜尋字詞),然後以該變數具現化新聞搜尋用戶端。

    var key = "YOUR-ACCESS-KEY";
    var searchTerm = "Quantum Computing";
    var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(key));
    

傳送要求並剖析結果

  1. 使用用戶端將搜尋要求傳送至 Bing 新聞搜尋服務:

    var newsResults = client.News.SearchAsync(query: searchTerm, market: "en-us", count: 10).Result;
    
  2. 如果傳回任何結果,請加以剖析:

    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 的 Bing 新聞搜尋用戶端程式庫開始搜尋新聞。 雖然 Bing 新聞搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。

Prerequisites

使用 Maven、Gradle 或另一個相依性管理系統,來安裝 Bing 新聞搜尋用戶端程式庫相依性。 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 資源,開始使用 Bing 新聞搜尋 API:

Bing 搜尋 v7 資源

  • 您可以透過 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;

建立搜尋用戶端與存放區認證

  1. 建立呼叫 getClient() 的方法,以傳回新的 NewsSearchAPIImpl 搜尋用戶端。 將您的端點新增為新 NewsSearchAPIImpl 物件的第一個參數,並新增 ServiceClientCredentials 物件來儲存您的認證。

    public static NewsSearchAPIImpl getClient(final String subscriptionKey) {
        return new NewsSearchAPIImpl("https://api.cognitive.microsoft.com/bing/v7.0/",
                new ServiceClientCredentials() {
                });
    }
    
  2. 若要建立 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);
                        }
                    });
        }
    });
    

傳送及接收搜尋要求

  1. 建立呼叫 getClient() 的方法,並將搜尋要求傳送至 Bing 新聞搜尋服務。 以 market 和 count 參數來篩選搜尋,然後列印第一個新聞結果的相關資訊:名稱、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!");
        }
    
    }
    
    
  2. 將您的搜尋方法新增至 main() 方法,以執行程式碼。

    public static void main(String[] args) {
        String subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
        NewsSearchSDK.newsSearch(subscriptionKey);
    }
    

後續步驟

使用本快速入門,透過適用於 JavaScript 的 Bing 新聞搜尋用戶端程式庫開始搜尋新聞。 雖然 Bing 新聞搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。

Prerequisites

  • 最新版的 Node.js
  • 適用於 JavaScript 的 Bing 新聞搜尋 SDK
    • 若要安裝,請執行 npm install @azure/cognitiveservices-newssearch
  • 來自 @azure/ms-rest-azure-js 套件中的 CognitiveServicesCredentials 類別,用來驗證用戶端。
    • 若要安裝,請執行 npm install @azure/ms-rest-azure-js

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 新聞搜尋 API:

Bing 搜尋 v7 資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 使用免費定價層來試用服務,之後可升級至付費層以用於實際執行環境。

多服務資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。

建立應用程式並將其初始化

  1. 建立 CognitiveServicesCredentials 執行個體。 針對您的訂用帳戶金鑰和搜尋字詞建立變數。

    const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
    let credentials = new CognitiveServicesCredentials('YOUR-ACCESS-KEY');
    let search_term = 'Winter Olympics'
    
  2. 具現化用戶端:

    const NewsSearchAPIClient = require('@azure/cognitiveservices-newssearch');
    let client = new NewsSearchAPIClient(credentials);
    

傳送搜尋查詢

  1. 使用用戶端以使用查詢字詞搜尋,本例中使用 "Winter Olympics":

    client.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 的 Bing 新聞搜尋用戶端程式庫開始搜尋新聞。 雖然 Bing 新聞搜尋具有與大部分程式設計語言相容的 REST API,但此用戶端程式庫可提供簡單的方法,將服務整合到您的應用程式。 此範例的原始程式碼可以在 GitHub 上找到。

Prerequisites

建議使用虛擬環境來開發 Python。 您可以使用 venv 模組來安裝和初始化虛擬環境。 您必須安裝適用於 Python 2.7 的 virtualenv。 您可以使用下列命令建立虛擬環境:

python -m venv mytestenv

您可以使用下列命令安裝 Bing 新聞搜尋用戶端程式庫相依性:

python -m pip install azure-cognitiveservices-search-newssearch

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 新聞搜尋 API:

Bing 搜尋 v7 資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 使用免費定價層來試用服務,之後可升級至付費層以用於實際執行環境。

多服務資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。

建立應用程式並將其初始化

  1. 在您最愛的 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"
    

初始化用戶端並傳送要求

  1. 建立 CognitiveServicesCredentials 執行個體。

    client = NewsSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    
  2. 將搜尋查詢傳送至 Bing 新聞搜尋 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..")

後續步驟