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

警告

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

Bing Web 搜尋用戶端程式庫可讓您輕鬆地將 Bing Web 搜尋整合到 C# 應用程式。 在本快速入門中,您將了解如何具現化用戶端、傳送要求,以及列印回應。

要立即查看程式碼嗎? GitHub 中提供適用於 .NET 的 Bing 搜尋用戶端程式庫的範例。

Prerequisites

以下是執行本快速入門之前的幾個必備項目:

建立 Azure 資源

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

Bing 搜尋 v7 資源

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

多服務資源

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

建立專案並安裝相依性

提示

GitHub 取得最新程式碼作為 Visual Studio 解決方案。

第一個步驟是建立新的主控台專案。 如需設定主控台專案的說明,請參閱 Hello World - 您的第一個程式 (C# 程式設計手冊)。 若要在您的應用程式中使用 Bing Web 搜尋 SDK,您必須使用 NuGet 套件管理員安裝 Microsoft.Azure.CognitiveServices.Search.WebSearch

Web 搜尋 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;

建立專案 Scaffolding

當您建立新的主控台專案時,應該就已建立應用程式的命名空間和類別。 您的程式看起來應該像此範例:

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);
    }
}

處理回應

接下來,讓我們新增一些程式碼來剖析回應並列印結果。 若第一個網頁、影像、新聞文章和影片存在於回應物件中,則會列印其 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 搜尋 API,讓我們看看一些函式,以突顯 SDK 在改善查詢和篩選結果方面的實用性。 每個函式都可以新增至上一節所建立的 C# 應用程式。

限制 Bing 所傳回的結果數目

這個範例會使用 countoffset 參數,來限制「西雅圖最佳餐廳」傳回的結果數目。 第一個結果的 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. WebResultsWithCountAndOffset 新增至 main

    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. WebResultsWithCountAndOffset 新增至 main

    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_countpromotesafe_search 參數,來篩選 "音樂影片" 的搜尋結果。 第一個結果的 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. WebResultsWithCountAndOffset 新增至 main

    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 搜尋用戶端程式庫可讓您輕鬆地將 Bing Web 搜尋整合到 JAVA 應用程式。 在本快速入門中,您將了解如何傳送要求、接收 JSON 回應,以及篩選和剖析結果。

要立即查看程式碼嗎? GitHub 中提供適用於 JAVA 的 Bing 搜尋用戶端程式庫的範例。

Prerequisites

以下是執行本快速入門之前的幾個必備項目:

建立 Azure 資源

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

Bing 搜尋 v7 資源

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

多服務資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 針對您的應用程式,跨多個 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.

}

建構要求

runSample 方法 (位於 BingWebSearchSample 類別中) 會建構要求。 將此程式碼複製到您的應用程式:

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...

處理回應

接下來,讓我們新增一些程式碼來剖析回應並列印結果。 當第一個網頁、影像、新聞文章和影片出現在回應物件中時,將會列印其 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 搜尋用戶端程式庫可讓您輕鬆地將 Bing Web 搜尋整合到 Node.js 應用程式。 在本快速入門中,您將了解如何具現化用戶端、傳送要求,以及列印回應。

要立即查看程式碼嗎? GitHub 中提供適用於 JavaScript 的 Bing 搜尋用戶端程式庫的範例。

Prerequisites

以下是執行本快速入門之前的幾個必備項目:

  • Node.js 6 (英文) 或更新版本
  • 訂用帳戶金鑰

建立 Azure 資源

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

Bing 搜尋 v7 資源

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

多服務資源

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。
  • 針對您的應用程式,跨多個 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 搜尋。 如果回應包含 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 搜尋用戶端程式庫可讓您輕鬆地將 Bing Web 搜尋整合到 Python 應用程式。 在本快速入門中,您將了解如何傳送要求、接收 JSON 回應,以及篩選和剖析結果。

要立即查看程式碼嗎? GitHub 中提供適用於 Python 的 Bing 搜尋用戶端程式庫的範例。

必要條件

Bing Web 搜尋 SDK 與 Python 2.7 或 3.6+ 相容。 建議在虛擬環境下使用此快速入門。

  • Python 2.7 或 3.6+
  • 適用於 Python 2.7 的 virtualenv (英文)
  • 適用於 Python 3.x 的 venv (英文)

建立 Azure 資源

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

Bing 搜尋 v7 資源

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

多服務資源

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

建立及設定您的虛擬環境

Python 2.x 和 Python 3.x 在安裝和設定虛擬環境方面各有不同的指示。 請遵循下列步驟來建立和初始化您的虛擬環境。

Python 2.x

使用適用於 Python 2.7 的 virtualenv 來建立虛擬環境:

virtualenv mytestenv

啟動您的環境:

cd mytestenv
source bin/activate

安裝 Bing Web 搜尋 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 搜尋 SDK 相依性:

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

建立用戶端並列印您的第一個結果

既然您已設定虛擬環境並安裝相依性,讓我們來建立用戶端。 用戶端會處理對 Bing Web 搜尋 API 提出的要求及其回應。

如果回應包含網頁、影像、新聞或影片,則會列印各項的第一個結果。

  1. 在您慣用的 IDE 或編輯器建立新的 Python 專案。

  2. 將此範例程式碼複製到您的專案。 endpoint 可以是下方的全域端點,也可以是 Azure 入口網站中針對您的資源所顯示的自訂子網域端點。:

    # 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 搜尋 API,讓我們看看一些函式。 下列幾節將特別說明可用來改善查詢和篩選結果的 SDK 功能。 每個函式都可以新增至您在上一節所建立的 Python 程式。

限制 Bing 所傳回的結果數目

這個範例會使用 countoffset 參數,來限制以 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_filterfreshness 參數,來篩選以 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_countpromotesafe_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. 執行程式。

清除資源

此專案使用完畢時,請務必從程式的程式碼中移除訂用帳戶金鑰,並停用虛擬環境。

後續步驟

另請參閱