クイック スタート:Bing Web Search クライアント ライブラリを使用する

警告

2020 年 10 月 30 日に、Bing Search API は Azure AI サービスから Bing Search サービスに移行されました。 このドキュメントは、参考用としてのみ提供されています。 更新されたドキュメントについては、Bing search API のドキュメントを参照してください。 Bing 検索用の新しい Azure リソースを作成する手順については、「Azure Marketplace から Bing Search リソースを作成する」を参照してください。

Bing Web Search クライアント ライブラリを使用すると、C# アプリケーションに Bing Web Search を簡単に統合することができます。 このクイック スタートでは、クライアントをインスタンス化し、要求を送信して、応答を出力する方法を学習します。

今すぐコードを確認したい場合は、 .NET 用の Bing Search クライアント ライブラリのサンプルは、GitHub で入手できます。

前提条件

このクイック スタートを実行するには、以下のものが必要です。

Azure リソースを作成する

次のいずれかの Azure リソースを作成して、Bing Web Search API の使用を開始します。

Bing Search v7 リソース

  • ご自身でリソースを削除するまでは Azure portal からご利用いただけます。
  • Free 価格レベルを使ってサービスを試用し、後から運用環境用の有料レベルにアップグレードします。

マルチサービス リソース

  • ご自身でリソースを削除するまでは Azure portal からご利用いただけます。
  • 複数の Azure AI サービス全体で同じキーとエンドポイントをアプリケーションに使用します。

プロジェクトの作成と依存関係のインストール

ヒント

最新のコードを Visual Studio ソリューションとして GitHub から取得してください。

最初の手順で、新しいコンソール プロジェクトを作成します。 コンソール プロジェクトの設定で支援が必要な場合は、「Hello World -- 最初のプログラム (C# プログラミング ガイド)」を参照してください。 アプリケーションで Bing Web Search SDK を使用するには、NuGet パッケージ マネージャーを使用して Microsoft.Azure.CognitiveServices.Search.WebSearch をインストールする必要があります。

Web Search SDK パッケージによって、以下のものもインストールされます。

  • Microsoft.Rest.ClientRuntime
  • Microsoft.Rest.ClientRuntime.Azure
  • Newtonsoft.Json

依存関係の宣言

Visual Studio または Visual Studio Code でプロジェクトを開き、次の依存関係をインポートします。

using System;
using System.Collections.Generic;
using Microsoft.Azure.CognitiveServices.Search.WebSearch;
using Microsoft.Azure.CognitiveServices.Search.WebSearch.Models;
using System.Linq;
using System.Threading.Tasks;

プロジェクトのスキャフォールディングの作成

新しいコンソール プロジェクトを作成したときに、アプリケーションの名前空間とクラスが作成されたはずです。 プログラムは次の例のようになっているものと思われます。

namespace WebSearchSDK
{
    class YOUR_PROGRAM
    {

        // The code in the following sections goes here.

    }
}

以降のセクションでは、このクラス内にサンプル アプリケーションを構築します。

要求の構築

このコードは、検索クエリを構築します。

public static async Task WebResults(WebSearchClient client)
{
    try
    {
        var webData = await client.Web.SearchAsync(query: "Yosemite National Park");
        Console.WriteLine("Searching for \"Yosemite National Park\"");

        // Code for handling responses is provided in the next section...

    }
    catch (Exception ex)
    {
        Console.WriteLine("Encountered exception. " + ex.Message);
    }
}

応答の処理

次に、応答を解析し、結果を出力するコードを追加してみましょう。 最初の Web ページ、画像、ニュース記事、およびビデオの NameUrl が出力されます (応答オブジェクトに含まれている場合)。

if (webData?.WebPages?.Value?.Count > 0)
{
    // find the first web page
    var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();

    if (firstWebPagesResult != null)
    {
        Console.WriteLine("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("Didn't find any web pages...");
    }
}
else
{
    Console.WriteLine("Didn't find any web pages...");
}

/*
 * Images
 * If the search response contains images, the first result's name
 * and url are printed.
 */
if (webData?.Images?.Value?.Count > 0)
{
    // find the first image result
    var firstImageResult = webData.Images.Value.FirstOrDefault();

    if (firstImageResult != null)
    {
        Console.WriteLine("Image Results # {0}", webData.Images.Value.Count);
        Console.WriteLine("First Image result name: {0} ", firstImageResult.Name);
        Console.WriteLine("First Image result URL: {0} ", firstImageResult.ContentUrl);
    }
    else
    {
        Console.WriteLine("Didn't find any images...");
    }
}
else
{
    Console.WriteLine("Didn't find any images...");
}

/*
 * News
 * If the search response contains news articles, the first result's name
 * and url are printed.
 */
if (webData?.News?.Value?.Count > 0)
{
    // find the first news result
    var firstNewsResult = webData.News.Value.FirstOrDefault();

    if (firstNewsResult != null)
    {
        Console.WriteLine("\r\nNews Results # {0}", webData.News.Value.Count);
        Console.WriteLine("First news result name: {0} ", firstNewsResult.Name);
        Console.WriteLine("First news result URL: {0} ", firstNewsResult.Url);
    }
    else
    {
        Console.WriteLine("Didn't find any news articles...");
    }
}
else
{
    Console.WriteLine("Didn't find any news articles...");
}

/*
 * Videos
 * If the search response contains videos, the first result's name
 * and url are printed.
 */
if (webData?.Videos?.Value?.Count > 0)
{
    // find the first video result
    var firstVideoResult = webData.Videos.Value.FirstOrDefault();

    if (firstVideoResult != null)
    {
        Console.WriteLine("\r\nVideo Results # {0}", webData.Videos.Value.Count);
        Console.WriteLine("First Video result name: {0} ", firstVideoResult.Name);
        Console.WriteLine("First Video result URL: {0} ", firstVideoResult.ContentUrl);
    }
    else
    {
        Console.WriteLine("Didn't find any videos...");
    }
}
else
{
    Console.WriteLine("Didn't find any videos...");
}

main メソッドの宣言

このアプリケーションの main メソッドには、クライアントをインスタンス化し、subscriptionKey を検証して、WebResults を呼び出すコードが含まれています。 続行する前に、ご自分の Azure アカウントの有効なサブスクリプション キーを入力してください。

static async Task Main(string[] args)
{
    var client = new WebSearchClient(new ApiKeyServiceClientCredentials("YOUR_SUBSCRIPTION_KEY"));

    await WebResults(client);

    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
}

アプリケーションの実行

アプリケーションを実行してみましょう。

dotnet run

関数の定義と結果のフィルター処理

これで Bing Web Search API の最初の呼び出しを実行できたので、次は SDK 機能がよくわかるいくつかの関数を調べて、クエリとフィルター処理の結果を調整しましょう。 各関数は、前のセクションで作成した C# アプリケーションに追加することができます。

Bing から返される結果の数の制限

このサンプルでは、count パラメーターと offset パラメーターを使用して、"Best restaurants in Seattle" (シアトルで最高のレストラン) に対して返される結果の数を制限しています。 最初の結果の NameUrl が出力されます。

  1. このコードをコンソール プロジェクトに追加します。

    public static async Task WebResultsWithCountAndOffset(WebSearchClient client)
    {
        try
        {
            var webData = await client.Web.SearchAsync(query: "Best restaurants in Seattle", offset: 10, count: 20);
            Console.WriteLine("\r\nSearching for \" Best restaurants in Seattle \"");
    
            if (webData?.WebPages?.Value?.Count > 0)
            {
                var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();
    
                if (firstWebPagesResult != null)
                {
                    Console.WriteLine("Web 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 first web result!");
                }
            }
            else
            {
                Console.WriteLine("Didn't see any Web data..");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Encountered exception. " + ex.Message);
        }
    }
    
  2. WebResultsWithCountAndOffsetmain に追加します。

    static async Task Main(string[] args)
    {
        var client = new WebSearchClient(new ApiKeyServiceClientCredentials("YOUR_SUBSCRIPTION_KEY"));
    
        await WebResults(client);
        // Search with count and offset...
        await WebResultsWithCountAndOffset(client);  
    
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
    
  3. アプリケーションを実行します。

ニュースのフィルター処理

このサンプルでは、response_filter パラメーターを使用して、検索結果をフィルター処理します。 返される検索結果は、"Microsoft" のニュース記事に限定されます。 最初の結果の NameUrl が出力されます。

  1. このコードをコンソール プロジェクトに追加します。

    public static async Task WebSearchWithResponseFilter(WebSearchClient client)
    {
        try
        {
            IList<string> responseFilterstrings = new List<string>() { "news" };
            var webData = await client.Web.SearchAsync(query: "Microsoft", responseFilter: responseFilterstrings);
            Console.WriteLine("\r\nSearching for \" Microsoft \" with response filter \"news\"");
    
            if (webData?.News?.Value?.Count > 0)
            {
                var firstNewsResult = webData.News.Value.FirstOrDefault();
    
                if (firstNewsResult != null)
                {
                    Console.WriteLine("News Results #{0}", webData.News.Value.Count);
                    Console.WriteLine("First news result name: {0} ", firstNewsResult.Name);
                    Console.WriteLine("First news result URL: {0} ", firstNewsResult.Url);
                }
                else
                {
                    Console.WriteLine("Couldn't find first News results!");
                }
            }
            else
            {
                Console.WriteLine("Didn't see any News data..");
            }
    
        }
        catch (Exception ex)
        {
            Console.WriteLine("Encountered exception. " + ex.Message);
        }
    }
    
  2. WebResultsWithCountAndOffsetmain に追加します。

    static Task Main(string[] args)
    {
        var client = new WebSearchClient(new ApiKeyServiceClientCredentials("YOUR_SUBSCRIPTION_KEY"));
    
        await WebResults(client);
        // Search with count and offset...
        await WebResultsWithCountAndOffset(client);  
        // Search with news filter...
        await WebSearchWithResponseFilter(client);
    
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
    
  3. アプリケーションを実行します。

セーフ サーチ、回答数、昇格フィルターの使用

このサンプルでは、answer_countpromote、および safe_search パラメーターを使用して、検索結果を "Music Videos" でフィルター処理します。 最初の結果の NameContentUrl が表示されます。

  1. このコードをコンソール プロジェクトに追加します。

    public static async Task WebSearchWithAnswerCountPromoteAndSafeSearch(WebSearchClient client)
    {
        try
        {
            IList<string> promoteAnswertypeStrings = new List<string>() { "videos" };
            var webData = await client.Web.SearchAsync(query: "Music Videos", answerCount: 2, promote: promoteAnswertypeStrings, safeSearch: SafeSearch.Strict);
            Console.WriteLine("\r\nSearching for \"Music Videos\"");
    
            if (webData?.Videos?.Value?.Count > 0)
            {
                var firstVideosResult = webData.Videos.Value.FirstOrDefault();
    
                if (firstVideosResult != null)
                {
                    Console.WriteLine("Video Results # {0}", webData.Videos.Value.Count);
                    Console.WriteLine("First Video result name: {0} ", firstVideosResult.Name);
                    Console.WriteLine("First Video result URL: {0} ", firstVideosResult.ContentUrl);
                }
                else
                {
                    Console.WriteLine("Couldn't find videos results!");
                }
            }
            else
            {
                Console.WriteLine("Didn't see any data..");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Encountered exception. " + ex.Message);
        }
    }
    
  2. WebResultsWithCountAndOffsetmain に追加します。

    static async Task Main(string[] args)
    {
        var client = new WebSearchClient(new ApiKeyServiceClientCredentials("YOUR_SUBSCRIPTION_KEY"));
    
        await WebResults(client);
        // Search with count and offset...
        await WebResultsWithCountAndOffset(client);  
        // Search with news filter...
        await WebSearchWithResponseFilter(client);
        // Search with answer count, promote, and safe search
        await WebSearchWithAnswerCountPromoteAndSafeSearch(client);
    
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
    
  3. アプリケーションを実行します。

リソースをクリーンアップする

このプロジェクトの使用を終了するときに、アプリケーションのコードからサブスクリプション キーを必ず削除してください。

次のステップ

Bing Web Search クライアント ライブラリを使用すると、Java アプリケーションに Bing Web Search を簡単に統合することができます。 このクイック スタートでは、要求を送信し、JSON 応答を受け取って、結果をフィルター処理および解析する方法を学習します。

今すぐコードを確認したい場合は、 Java 用の Bing Search クライアント ライブラリのサンプルは、GitHub で入手できます。

前提条件

このクイック スタートを実行するには、以下のものが必要です。

  • JDK 7 または 8
  • Apache Maven または普段使用しているビルド オートメーション ツール
  • サブスクリプション キー

Azure リソースを作成する

次のいずれかの Azure リソースを作成して、Bing Web Search API の使用を開始します。

Bing Search v7 リソース

  • ご自身でリソースを削除するまでは Azure portal からご利用いただけます。
  • Free 価格レベルを使ってサービスを試用し、後から運用環境用の有料レベルにアップグレードします。

マルチサービス リソース

  • ご自身でリソースを削除するまでは Azure portal からご利用いただけます。
  • 複数の Azure AI サービス全体で同じキーとエンドポイントをアプリケーションに使用します。

プロジェクトを作成して POM ファイルを設定する

Maven または普段使用しているビルド オートメーション ツールを使用して、新しい Java プロジェクトを作成します。 Maven を使用している場合は、以下の行をプロジェクト オブジェクト モデル (POM) ファイルに追加します。 すべての mainClass を実際のアプリケーションに置き換えます。

<build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.4.0</version>
        <configuration>
          <!--Your comment
            Replace the mainClass with the path to your Java application.
            It should begin with com and doesn't require the .java extension.
            For example: com.bingwebsearch.app.BingWebSearchSample. This maps to
            The following directory structure:
            src/main/java/com/bingwebsearch/app/BingWebSearchSample.java.
          -->
          <mainClass>com.path.to.your.app.APP_NAME</mainClass>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>attached</goal>
            </goals>
            <configuration>
              <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
              </descriptorRefs>
              <archive>
                <manifest>
                  <!--Your comment
                    Replace the mainClass with the path to your Java application.
                    For example: com.bingwebsearch.app.BingWebSearchSample.java.
                    This maps to the following directory structure:
                    src/main/java/com/bingwebsearch/app/BingWebSearchSample.java.
                  -->
                  <mainClass>com.path.to.your.app.APP_NAME.java</mainClass>
                </manifest>
              </archive>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure</artifactId>
      <version>1.9.0</version>
    </dependency>
    <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>3.3</version>
    </dependency>
    <dependency>
      <groupId>com.microsoft.azure.cognitiveservices</groupId>
      <artifactId>azure-cognitiveservices-websearch</artifactId>
      <version>1.0.1</version>
    </dependency>
  </dependencies>

依存関係の宣言

普段使用している IDE またはエディターでプロジェクトを開き、以下の依存関係をインポートします。

import com.microsoft.azure.cognitiveservices.search.websearch.BingWebSearchAPI;
import com.microsoft.azure.cognitiveservices.search.websearch.BingWebSearchManager;
import com.microsoft.azure.cognitiveservices.search.websearch.models.ImageObject;
import com.microsoft.azure.cognitiveservices.search.websearch.models.NewsArticle;
import com.microsoft.azure.cognitiveservices.search.websearch.models.SearchResponse;
import com.microsoft.azure.cognitiveservices.search.websearch.models.VideoObject;
import com.microsoft.azure.cognitiveservices.search.websearch.models.WebPage;

プロジェクトを Maven で作成した場合、パッケージは既に宣言されています。 それ以外の場合は、ここでパッケージを宣言します。 次に例を示します。

package com.bingwebsearch.app

BingWebSearchSample クラスの宣言

BingWebSearchSample クラスを宣言します。 これには、main メソッドなど、ほとんどのコードが含まれます。

public class BingWebSearchSample {

// The code in the following sections goes here.

}

要求の構築

BingWebSearchSample クラスに存在する runSample メソッドは、要求を構築します。 次のコードをアプリケーションにコピーします。

public static boolean runSample(BingWebSearchAPI client) {
    /*
     * This function performs the search.
     *
     * @param client instance of the Bing Web Search API client
     * @return true if sample runs successfully
     */
    try {
        /*
         * Performs a search based on the .withQuery and prints the name and
         * url for the first web pages, image, news, and video result
         * included in the response.
         */
        System.out.println("Searched Web for \"Xbox\"");
        // Construct the request.
        SearchResponse webData = client.bingWebs().search()
            .withQuery("Xbox")
            .withMarket("en-us")
            .withCount(10)
            .execute();

// Code continues in the next section...

応答の処理

次に、応答を解析し、結果を出力するコードを追加してみましょう。 最初の Web ページ、画像、ニュース記事、および動画の nameurl が出力されます (応答オブジェクトに含まれている場合)。

/*
* WebPages
* If the search response has web pages, the first result's name
* and url are printed.
*/
if (webData != null && webData.webPages() != null && webData.webPages().value() != 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 the first web result!");
    }
} else {
    System.out.println("Didn't find any web pages...");
}
/*
 * Images
 * If the search response has images, the first result's name
 * and url are printed.
 */
if (webData != null && webData.images() != null && webData.images().value() != null &&
        webData.images().value().size() > 0) {
    // find the first image result
    ImageObject firstImageResult = webData.images().value().get(0);

    if (firstImageResult != null) {
        System.out.println(String.format("Image Results#%d", webData.images().value().size()));
        System.out.println(String.format("First Image result name: %s ", firstImageResult.name()));
        System.out.println(String.format("First Image result URL: %s ", firstImageResult.contentUrl()));
    } else {
        System.out.println("Couldn't find the first image result!");
    }
} else {
    System.out.println("Didn't find any images...");
}
/*
 * News
 * If the search response has news articles, the first result's name
 * and url are printed.
 */
if (webData != null && webData.news() != null && webData.news().value() != null &&
        webData.news().value().size() > 0) {
    // find the first news result
    NewsArticle firstNewsResult = webData.news().value().get(0);
    if (firstNewsResult != null) {
        System.out.println(String.format("News Results#%d", webData.news().value().size()));
        System.out.println(String.format("First news result name: %s ", firstNewsResult.name()));
        System.out.println(String.format("First news result URL: %s ", firstNewsResult.url()));
    } else {
        System.out.println("Couldn't find the first news result!");
    }
} else {
    System.out.println("Didn't find any news articles...");
}

/*
 * Videos
 * If the search response has videos, the first result's name
 * and url are printed.
 */
if (webData != null && webData.videos() != null && webData.videos().value() != null &&
        webData.videos().value().size() > 0) {
    // find the first video result
    VideoObject firstVideoResult = webData.videos().value().get(0);

    if (firstVideoResult != null) {
        System.out.println(String.format("Video Results#%s", webData.videos().value().size()));
        System.out.println(String.format("First Video result name: %s ", firstVideoResult.name()));
        System.out.println(String.format("First Video result URL: %s ", firstVideoResult.contentUrl()));
    } else {
        System.out.println("Couldn't find the first video result!");
    }
} else {
    System.out.println("Didn't find any videos...");
}

main メソッドの宣言

このアプリケーションの main メソッドには、クライアントをインスタンス化し、subscriptionKey を検証して、runSample を呼び出すコードが含まれています。 続行する前に、ご自分の Azure アカウントの有効なサブスクリプション キーを入力してください。

public static void main(String[] args) {
    try {
        // Enter a valid subscription key for your account.
        final String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
        // Instantiate the client.
        BingWebSearchAPI client = BingWebSearchManager.authenticate(subscriptionKey);
        // Make a call to the Bing Web Search API.
        runSample(client);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

プログラムの実行

最後の手順で、プログラムを実行します。

mvn compile exec:java

リソースをクリーンアップする

このプロジェクトの使用を終了するときに、プログラムのコードからサブスクリプション キーを必ず削除してください。

次のステップ

関連項目

Bing Web Search クライアント ライブラリを使用すると、Node.js アプリケーションに Bing Web Search を簡単に統合することができます。 このクイック スタートでは、クライアントをインスタンス化し、要求を送信して、応答を出力する方法を学習します。

今すぐコードを確認したい場合は、 JavaScript 用の Bing Search クライアント ライブラリのサンプルは、GitHub で入手できます。

前提条件

このクイック スタートを実行するには、以下のものが必要です。

  • Node.js 6 以降
  • サブスクリプション キー

Azure リソースを作成する

次のいずれかの Azure リソースを作成して、Bing Web Search API の使用を開始します。

Bing Search v7 リソース

  • ご自身でリソースを削除するまでは Azure portal からご利用いただけます。
  • Free 価格レベルを使ってサービスを試用し、後から運用環境用の有料レベルにアップグレードします。

マルチサービス リソース

  • ご自身でリソースを削除するまでは Azure portal からご利用いただけます。
  • 複数の Azure AI サービス全体で同じキーとエンドポイントをアプリケーションに使用します。

開発環境を設定する

まず、Node.js プロジェクトの開発環境を設定します。

  1. プロジェクト用の新規ディレクトリを作成します。

    mkdir YOUR_PROJECT
    
  2. 新しいパッケージ ファイルを作成します。

    cd YOUR_PROJECT
    npm init
    
  3. ここで、いくつかの Azure モジュールをインストールし、package.json に追加します。

    npm install --save @azure/cognitiveservices-websearch
    npm install --save @azure/ms-rest-azure-js
    

プロジェクトの作成と必要なモジュールの宣言

package.json と同じディレクトリで、普段使用している IDE またはエディターで新しい Node.js プロジェクトを作成します。 (例: sample.js)。

次に、このコードをプロジェクトにコピーします。 前のセクションでインストールしたモジュールが読み込まれます。

const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
const WebSearchAPIClient = require('@azure/cognitiveservices-websearch');

クライアントのインスタンス化

次のコードは、クライアントをインスタンス化し、@azure/cognitiveservices-websearch モジュールを使用します。 続行する前に、ご自分の Azure アカウントの有効なサブスクリプション キーを入力してください。

let credentials = new CognitiveServicesCredentials('YOUR-ACCESS-KEY');
let webSearchApiClient = new WebSearchAPIClient(credentials);

要求の実行と結果の出力

クライアントを使用して、Bing Web search に検索クエリを送信します。 応答に properties 配列のいずれかの項目の結果が含まれている場合、result.value がコンソールに出力されます。

webSearchApiClient.web.search('seahawks').then((result) => {
    let properties = ["images", "webPages", "news", "videos"];
    for (let i = 0; i < properties.length; i++) {
        if (result[properties[i]]) {
            console.log(result[properties[i]].value);
        } else {
            console.log(`No ${properties[i]} data`);
        }
    }
}).catch((err) => {
    throw err;
})

プログラムの実行

最後の手順で、プログラムを実行します。

リソースをクリーンアップする

このプロジェクトの使用を終了するときに、プログラムのコードからサブスクリプション キーを必ず削除してください。

次のステップ

参照

Bing Web Search クライアント ライブラリを使用すると、Python アプリケーションに Bing Web Search を簡単に統合することができます。 このクイック スタートでは、要求を送信し、JSON 応答を受け取って、結果をフィルター処理および解析する方法を学習します。

今すぐコードを確認したい場合は、 Python 用の Bing Search クライアント ライブラリのサンプルは、GitHub で入手できます。

前提条件

Bing Web Search SDK は、Python 2.7 または 3.6 以上と互換性があります。 このクイック スタートには仮想環境を使用することをお勧めします。

  • Python 2.7 または 3.6 以降
  • Python 2.7 向けの virtualenv
  • Python 3.x 向けの venv

Azure リソースを作成する

次のいずれかの Azure リソースを作成して、Bing Web Search API の使用を開始します。

Bing Search v7 リソース

  • ご自身でリソースを削除するまでは Azure portal からご利用いただけます。
  • Free 価格レベルを使ってサービスを試用し、後から運用環境用の有料レベルにアップグレードします。

マルチサービス リソース

  • ご自身でリソースを削除するまでは Azure portal からご利用いただけます。
  • 複数の Azure AI サービス全体で同じキーとエンドポイントをアプリケーションに使用します。

仮想環境の作成と構成

仮想環境の設定と構成の手順は、Python 2.x と Python 3.x では異なります。 仮想環境を作成して初期化するには、以下の手順に従います。

Python 2.x

次のように、Python 2.7 向け virtualenv を使用して仮想環境を作成します。

virtualenv mytestenv

環境をアクティブ化します。

cd mytestenv
source bin/activate

Bing Web Search SDK 依存関係をインストールします。

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

Python 3.x

次のように、Python 3.X 向け venv を使用して仮想環境を作成します。

python -m venv mytestenv

環境をアクティブ化します。

mytestenv\Scripts\activate.bat

Bing Web Search SDK 依存関係をインストールします。

cd mytestenv
python -m pip install azure-cognitiveservices-search-websearch

クライアントの作成と最初の結果の出力

これで仮想環境の設定と依存関係のインストールができたので、次はクライアントを作成します。 クライアントは、Bing Web Search API への要求と Bing Web Search API からの応答を処理します。

応答に Web ページ、画像、ニュース、または動画が含まれている場合は、それぞれの最初の結果が出力されます。

  1. 普段使用している IDE またはエディターで、新しい Python プロジェクトを作成します。

  2. このサンプル コードをプロジェクトにコピーします。 endpoint には、以下のグローバル エンドポイントを指定するか、Azure portal に表示される、リソースのカスタム サブドメイン エンドポイントを指定できます。

    # Import required modules.
    from azure.cognitiveservices.search.websearch import WebSearchClient
    from azure.cognitiveservices.search.websearch.models import SafeSearch
    from msrest.authentication import CognitiveServicesCredentials
    
    # Replace with your subscription key.
    subscription_key = "YOUR_SUBSCRIPTION_KEY"
    
    # Instantiate the client and replace with your endpoint.
    client = WebSearchClient(endpoint="YOUR_ENDPOINT", credentials=CognitiveServicesCredentials(subscription_key))
    
    # Make a request. Replace Yosemite if you'd like.
    web_data = client.web.search(query="Yosemite")
    print("\r\nSearched for Query# \" Yosemite \"")
    
    '''
    Web pages
    If the search response contains web pages, the first result's name and url
    are printed.
    '''
    if hasattr(web_data.web_pages, 'value'):
    
        print("\r\nWebpage Results#{}".format(len(web_data.web_pages.value)))
    
        first_web_page = web_data.web_pages.value[0]
        print("First web page name: {} ".format(first_web_page.name))
        print("First web page URL: {} ".format(first_web_page.url))
    
    else:
        print("Didn't find any web pages...")
    
    '''
    Images
    If the search response contains images, the first result's name and url
    are printed.
    '''
    if hasattr(web_data.images, 'value'):
    
        print("\r\nImage Results#{}".format(len(web_data.images.value)))
    
        first_image = web_data.images.value[0]
        print("First Image name: {} ".format(first_image.name))
        print("First Image URL: {} ".format(first_image.url))
    
    else:
        print("Didn't find any images...")
    
    '''
    News
    If the search response contains news, the first result's name and url
    are printed.
    '''
    if hasattr(web_data.news, 'value'):
    
        print("\r\nNews Results#{}".format(len(web_data.news.value)))
    
        first_news = web_data.news.value[0]
        print("First News name: {} ".format(first_news.name))
        print("First News URL: {} ".format(first_news.url))
    
    else:
        print("Didn't find any news...")
    
    '''
    If the search response contains videos, the first result's name and url
    are printed.
    '''
    if hasattr(web_data.videos, 'value'):
    
        print("\r\nVideos Results#{}".format(len(web_data.videos.value)))
    
        first_video = web_data.videos.value[0]
        print("First Videos name: {} ".format(first_video.name))
        print("First Videos URL: {} ".format(first_video.url))
    
    else:
        print("Didn't find any videos...")
    
  3. SUBSCRIPTION_KEY を有効なサブスクリプション キーに置き換えます。

  4. YOUR_ENDPOINT をポータルのエンドポイント URL で置換し、エンドポイントから "bing/v7.0" セクションを削除します。

  5. プログラムを実行します。 (例: python your_program.py)。

関数の定義と結果のフィルター処理

Bing Web Search API の最初の呼び出しを行ったので、関数をいくつか見てみましょう。 以下のセクションでは、クエリを調整して結果をフィルター処理するための SDK の機能に注目します。 各関数は、前のセクションで作成した Python プログラムに追加することができます。

Bing から返される結果の数の制限

このサンプルでは、count パラメーターと offset パラメーターを使用して、SDK の search メソッドによって返される結果の数を制限しています。 最初の結果の nameurl が出力されます。

  1. 次のコードを Python プロジェクトに追加します。

     # Declare the function.
     def web_results_with_count_and_offset(subscription_key):
         client = WebSearchAPI(CognitiveServicesCredentials(subscription_key))
    
         try:
             '''
             Set the query, offset, and count using the SDK's search method. See:
             https://learn.microsoft.com/python/api/azure-cognitiveservices-search-websearch/azure.cognitiveservices.search.websearch.operations.weboperations?view=azure-python.
             '''
             web_data = client.web.search(query="Best restaurants in Seattle", offset=10, count=20)
             print("\r\nSearching for \"Best restaurants in Seattle\"")
    
             if web_data.web_pages.value:
                 '''
                 If web pages are available, print the # of responses, and the first and second
                 web pages returned.
                 '''
                 print("Webpage Results#{}".format(len(web_data.web_pages.value)))
    
                 first_web_page = web_data.web_pages.value[0]
                 print("First web page name: {} ".format(first_web_page.name))
                 print("First web page URL: {} ".format(first_web_page.url))
    
             else:
                 print("Didn't find any web pages...")
    
         except Exception as err:
             print("Encountered exception. {}".format(err))
    
  2. プログラムを実行します。

ニュースと鮮度のフィルター処理

このサンプルでは、response_filter パラメーターと freshness パラメーターを使用して、SDK の search メソッドによる検索結果をフィルター処理します。 返される検索結果は、ニュース記事と、Bing が過去 24 時間以内に検出したページだけに制限されます。 最初の結果の nameurl が出力されます。

  1. 次のコードを Python プロジェクトに追加します。

    # Declare the function.
    def web_search_with_response_filter(subscription_key):
        client = WebSearchAPI(CognitiveServicesCredentials(subscription_key))
        try:
            '''
            Set the query, response_filter, and freshness using the SDK's search method. See:
            https://learn.microsoft.com/python/api/azure-cognitiveservices-search-websearch/azure.cognitiveservices.search.websearch.operations.weboperations?view=azure-python.
            '''
            web_data = client.web.search(query="xbox",
                response_filter=["News"],
                freshness="Day")
            print("\r\nSearching for \"xbox\" with the response filter set to \"News\" and freshness filter set to \"Day\".")
    
            '''
            If news articles are available, print the # of responses, and the first and second
            articles returned.
            '''
            if web_data.news.value:
    
                print("# of news results: {}".format(len(web_data.news.value)))
    
                first_web_page = web_data.news.value[0]
                print("First article name: {} ".format(first_web_page.name))
                print("First article URL: {} ".format(first_web_page.url))
    
                print("")
    
                second_web_page = web_data.news.value[1]
                print("\nSecond article name: {} ".format(second_web_page.name))
                print("Second article URL: {} ".format(second_web_page.url))
    
            else:
                print("Didn't find any news articles...")
    
        except Exception as err:
            print("Encountered exception. {}".format(err))
    
    # Call the function.
    web_search_with_response_filter(subscription_key)
    
  2. プログラムを実行します。

セーフ サーチ、回答数、昇格フィルターの使用

このサンプルでは、answer_countpromote、および safe_search パラメーターを使用して、SDK の search メソッドによる検索結果をフィルター処理します。 最初の結果の nameurl が表示されます。

  1. 次のコードを Python プロジェクトに追加します。

    # Declare the function.
    def web_search_with_answer_count_promote_and_safe_search(subscription_key):
    
        client = WebSearchAPI(CognitiveServicesCredentials(subscription_key))
    
        try:
            '''
            Set the query, answer_count, promote, and safe_search parameters using the SDK's search method. See:
            https://learn.microsoft.com/python/api/azure-cognitiveservices-search-websearch/azure.cognitiveservices.search.websearch.operations.weboperations?view=azure-python.
            '''
            web_data = client.web.search(
                query="Niagara Falls",
                answer_count=2,
                promote=["videos"],
                safe_search=SafeSearch.strict  # or directly "Strict"
            )
            print("\r\nSearching for \"Niagara Falls\"")
    
            '''
            If results are available, print the # of responses, and the first result returned.
            '''
            if web_data.web_pages.value:
    
                print("Webpage Results#{}".format(len(web_data.web_pages.value)))
    
                first_web_page = web_data.web_pages.value[0]
                print("First web page name: {} ".format(first_web_page.name))
                print("First web page URL: {} ".format(first_web_page.url))
    
            else:
                print("Didn't see any Web data..")
    
        except Exception as err:
            print("Encountered exception. {}".format(err))
    
  2. プログラムを実行します。

リソースをクリーンアップする

このプロジェクトの使用を終了するときに、必ずプログラムのコードからサブスクリプション キーを削除し、仮想環境を非アクティブ化してください。

次のステップ

関連項目