快速入門:使用 Bing 自訂搜尋用戶端程式庫

警告

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

開始使用適用於 C# 的 Bing 自訂搜尋用戶端程式庫。 請遵循下列步驟來安裝套件,並試用基本工作的程式碼範例。 Bing 自訂搜尋 API 可讓您針對感興趣的主題,建立量身訂做且無廣告的搜尋經驗。 此範例的原始程式碼可以在 GitHub 上找到。

使用適用於 C# 的 Bing 自訂搜尋用戶端程式庫:

  • 從您的 Bing 自訂搜尋執行個體,在 Web 上尋找搜尋結果。

參考文件 | 程式庫來源程式碼 | 套件 (NuGet) | 範例

Prerequisites

  • 「Bing 自訂搜尋」執行個體。 請參閱快速入門:建立您的第一個 Bing 自訂搜尋執行個體,以取得詳細資訊。
  • Microsoft .NET Core
  • Visual Studio 2017 或更新版本的任何版本
  • 如果您使用 Linux/MacOS,則可以使用 Mono來執行此應用程式。
  • Bing 自訂搜尋 NuGet 套件。
    • 在 Visual Studio 的 [方案總管] 中,以滑鼠右鍵按一下專案,然後從功能表選取 [管理 NuGet 套件]。 安裝 Microsoft.Azure.CognitiveServices.Search.CustomSearch 套件。 安裝 NuGet 自訂搜尋套件也會一併安裝下列組件:
      • Microsoft.Rest.ClientRuntime
      • Microsoft.Rest.ClientRuntime.Azure
      • Newtonsoft.Json

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 自訂搜尋 API。

Bing 自訂搜尋資源

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

多服務資源

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

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

  1. 在 Visual Studio 中,建立新的 C# 主控台應用程式。 然後,將下列套件新增至您的專案。

    using System;
    using System.Linq;
    using Microsoft.Azure.CognitiveServices.Search.CustomSearch;
    
  2. 在您應用程式的主要方法中,使用 API 金鑰具現化搜尋用戶端。

    var client = new CustomSearchAPI(new ApiKeyServiceClientCredentials("YOUR-SUBSCRIPTION-KEY"));
    

傳送搜尋要求並接收回應

  1. 使用用戶端的 SearchAsync() 方法傳送搜尋查詢,並儲存回應。 請務必將 YOUR-CUSTOM-CONFIG-ID 取代為執行個體的組態識別碼 (您可以在 Bing 自訂搜尋入口網站中找到該識別碼)。 此範例會搜尋 "Xbox"。

    // This will look up a single query (Xbox).
    var webData = client.CustomInstance.SearchAsync(query: "Xbox", customConfig: Int32.Parse("YOUR-CUSTOM-CONFIG-ID")).Result;
    
  2. SearchAsync() 方法會傳回 WebData 物件。 使用物件來逐一查看找到的任何 WebPages。 此程式碼會找出第一個網頁結果,並列印網頁的 NameURL

    if (webData?.WebPages?.Value?.Count > 0)
    {
        // find the first web page
        var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();
    
        if (firstWebPagesResult != null)
        {
            Console.WriteLine("Number of webpage results {0}", webData.WebPages.Value.Count);
            Console.WriteLine("First web page name: {0} ", firstWebPagesResult.Name);
            Console.WriteLine("First web page URL: {0} ", firstWebPagesResult.Url);
        }
        else
        {
            Console.WriteLine("Couldn't find web results!");
        }
    }
    else
    {
        Console.WriteLine("Didn't see any Web data..");
    }
    

後續步驟

開始使用適用於 Java 的 Bing 自訂搜尋用戶端程式庫。 請遵循下列步驟來安裝套件,並試用基本工作的程式碼範例。 Bing 自訂搜尋 API 可讓您針對感興趣的主題,建立量身訂做且無廣告的搜尋經驗。 此範例的原始程式碼位於 GitHub

使用適用於 Java 的 Bing 自訂搜尋用戶端程式庫:

  • 從您的 Bing 自訂搜尋執行個體,在 Web 上尋找搜尋結果。

參考文件 | 程式庫原始程式碼 | 成品 (Maven) | 範例

必要條件

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 自訂搜尋 API。

Bing 自訂搜尋資源

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

多服務資源

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

從資源取得金鑰之後,請為名為 AZURE_BING_CUSTOM_SEARCH_API_KEY 的金鑰建立環境變數

建立新的 Gradle 專案

提示

如果您不是使用 Gradle,可以在 Maven 中央存放庫中找到其他相依性管理員的用戶端程式庫詳細資料。

在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立新的目錄,並瀏覽至該目錄。

mkdir myapp && cd myapp

從您的工作目錄執行 gradle init 命令。 此命令會建立 Gradle 的基本組建檔案,包括 build.gradle.kts檔案,該檔案在執行階段用於設定您的應用程式。

gradle init --type basic

出現選擇 DSL 的提示時,請選取 [Kotlin]。

安裝用戶端程式庫

找出 build.gradle.kts,並使用您慣用的 IDE 或文字編輯器加以開啟。 然後,在此組建組態中複製下列內容。 請務必在 dependencies 之下包含用戶端程式庫:

plugins {
    java
    application
}
application {
    mainClassName = "main.java.BingCustomSearchSample"
}
repositories {
    mavenCentral()
}
dependencies {
    compile("org.slf4j:slf4j-simple:1.7.25")
    compile("com.microsoft.azure.cognitiveservices:azure-cognitiveservices-customsearch:1.0.2")
}

建立範例應用程式的資料夾。 從工作目錄執行下列命令:

mkdir src/main/java

瀏覽至新的資料夾,並建立名為 BingCustomSearchSample.java 的檔案。 開啟該檔案,並新增下列 import 陳述式:

package main.java;

import com.microsoft.azure.cognitiveservices.search.customsearch.BingCustomSearchAPI;
import com.microsoft.azure.cognitiveservices.search.customsearch.BingCustomSearchManager;
import com.microsoft.azure.cognitiveservices.search.customsearch.models.SearchResponse;
import com.microsoft.azure.cognitiveservices.search.customsearch.models.WebPage;

建立名為 BingCustomSearchSample 的類別

public class BingCustomSearchSample {
}

在類別中,為資源的金鑰建立 main 方法和變數。 如果您在啟動應用程式後才建立環境變數,請先關閉執行該應用程式的編輯器、IDE 或殼層,再重新加以開啟,才能存取該變數。 您會在稍後定義方法。

public static void main(String[] args) {
    try {

        // Set the BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY and AZURE_BING_SAMPLES_CUSTOM_CONFIG_ID environment variables, 
        // then reopen your command prompt or IDE. If not, you may get an API key not found exception.
        final String subscriptionKey = System.getenv("BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY");
        // If you do not have a customConfigId, you can also use 1 as your value when setting your environment variable.
        final String customConfigId = System.getenv("AZURE_BING_SAMPLES_CUSTOM_CONFIG_ID");

        BingCustomSearchAPI client = BingCustomSearchManager.authenticate(subscriptionKey);

        runSample(client, customConfigId);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

物件模型

Bing 自訂搜尋用戶端是從 BingCustomSearchManager物件的 authenticate()方法建立的 BingCustomSearchAPI 物件。 您可以使用用戶端的 BingCustomInstances.search()方法來傳送搜尋要求。

API 回應是 SearchResponse 物件,其中包含搜尋查詢資訊和搜尋結果。

程式碼範例

這些程式碼片段說明如何使用適用於 Java 的 Bing 自訂搜尋用戶端程式庫來執行下列工作:

驗證用戶端

您的 main 方法應包含 BingCustomSearchManager物件,該物件會採用您的金鑰並呼叫其 authenticate()

BingCustomSearchAPI client = BingCustomSearchManager.authenticate(subscriptionKey);

從自訂搜尋執行個體中取得搜尋結果

使用用戶端的 BingCustomInstances.search()函式,將搜尋查詢傳送至您的自訂執行個體。 將 withCustomConfig 設為您的自訂組態識別碼,或預設為 1。 從 API 取得回應之後,檢查是否找到任何搜尋結果。 若是如此,請呼叫回應的 webPages().value().get() 函式並列印結果的名稱和 URL,以取得第一筆搜尋結果。

public static boolean runSample(BingCustomSearchAPI client, String customConfigId) {
    try {

        // This will search for "Xbox" using Bing Custom Search 
        //and print out name and url for the first web page in the results list

        System.out.println("Searching for Query: \"Xbox\"");
        SearchResponse webData = client.bingCustomInstances().search()
            .withCustomConfig(customConfigId != null ? Long.valueOf(customConfigId) : 0)
            .withQuery("Xbox")
            .withMarket("en-us")
            .execute();

        if (webData != null && webData.webPages() != null && webData.webPages().value().size() > 0)
        {
            // find the first web page
            WebPage firstWebPagesResult = webData.webPages().value().get(0);

            if (firstWebPagesResult != null) {
                System.out.println(String.format("Webpage Results#%d", webData.webPages().value().size()));
                System.out.println(String.format("First web page name: %s ", firstWebPagesResult.name()));
                System.out.println(String.format("First web page URL: %s ", firstWebPagesResult.url()));
            } else {
                System.out.println("Couldn't find web results!");
            }
        } else {
            System.out.println("Didn't see any Web data..");
        }

        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    }
    return false;
}

執行應用程式

從您專案的主目錄,使用下列命令建置應用程式:

gradle build

使用 run 目標執行應用程式:

gradle run

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除其關聯的任何其他資源。

後續步驟

開始使用適用於 Python 的 Bing 自訂搜尋用戶端程式庫。 請遵循下列步驟來安裝套件,並試用基本工作的程式碼範例。 Bing 自訂搜尋 API 可讓您針對感興趣的主題,建立量身訂做且無廣告的搜尋經驗。在 GitHub上可以找到此範例的原始程式碼。

使用適用於 Python 的 Bing 自訂搜尋用戶端程式庫:

  • 從您的 Bing 自訂搜尋執行個體,在 Web 上尋找搜尋結果。

參考文件 | 程式庫來源程式碼 | 套件 (PyPi) | 範例

Prerequisites

建立 Azure 資源

藉由建立下列其中一項 Azure 資源,開始使用 Bing 自訂搜尋 API。

Bing 自訂搜尋資源

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

多服務資源

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

安裝 Python 用戶端程式庫

使用下列命令安裝 Bing 自訂搜尋用戶端程式庫。

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

建立新的應用程式

在您慣用的編輯器或 IDE 中建立新的 Python 檔案,並新增下列匯入項目。

from azure.cognitiveservices.search.customsearch import CustomSearchClient
from msrest.authentication import CognitiveServicesCredentials

建立搜尋用戶端並傳送要求

  1. 建立訂用帳戶金鑰和端點的變數。

    subscription_key = 'your-subscription-key'
    endpoint = 'your-endpoint'
    
  2. 使用 CognitiveServicesCredentials 物件與訂用帳戶金鑰建立 CustomSearchClient 的執行個體。

    client = CustomSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    
  3. 透過 client.custom_instance.search() 傳送搜尋要求。 將搜尋字詞附加到 query 參數,並將 custom_config 設為您的自訂組態識別碼,以使用您的搜尋執行個體。 您可以按一下 [生產] 索引標籤,從 Bing 自訂搜尋入口網站取得您的識別碼。

    web_data = client.custom_instance.search(query="xbox", custom_config="your-configuration-id")
    

檢視搜尋結果

如果找到任何網頁搜尋結果,請取得第一個結果並列印其名稱、URL,以及找到的網頁總數。

if web_data.web_pages.value:
    first_web_result = web_data.web_pages.value[0]
    print("Web Pages result count: {}".format(len(web_data.web_pages.value)))
    print("First Web Page name: {}".format(first_web_result.name))
    print("First Web Page url: {}".format(first_web_result.url))
else:
    print("Didn't see any web data..")

後續步驟