快速入门:使用必应 Web 搜索客户端库

警告

2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅 必应搜索 API 文档。 有关为必应搜索创建新 Azure 资源的说明,请参阅 通过 Azure 市场创建必应搜索资源。

使用必应 Web 搜索客户端库,可以轻松地将必应 Web 搜索集成到 C# 应用程序中。 在本快速入门中,你将了解如何实例化客户端、发送请求并打印响应。

想要立即查看代码? GitHub 上提供了适用于 .NET 必应搜索客户端库的示例。

先决条件

在运行此快速入门之前,您需要准备以下事项:

创建 Azure 资源

通过创建以下 Azure 资源之一开始使用必应 Web 搜索 API:

必应搜索 v7 资源库

  • 可通过 Azure 门户使用,直到删除资源。
  • 使用免费定价层试用该服务,稍后升级到生产付费层。

多服务资源

  • 可通过 Azure 门户使用,直到删除资源。
  • 跨多个 Azure AI 服务对应用程序使用相同的密钥和终结点。

创建项目并安装依赖项

小提示

GitHub获取作为 Visual Studio 解决方案的最新代码。

第一步是创建新的控制台项目。 如果需要有关设置控制台项目的帮助,请参阅 Hello World - 你的第一个程序(C# 编程指南)。 若要在应用程序中使用必应 Web 搜索 SDK,需要使用 NuGet 包管理器安装 Microsoft.Azure.CognitiveServices.Search.WebSearch

Web 搜索 SDK 包 还会安装:

  • Microsoft.Rest.ClientRuntime(微软.Rest.客户端运行时)
  • 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);
    }
}

处理响应

接下来,让我们添加一些代码来分析响应并打印结果。 如果响应对象中存在,则打印与第一个网页、图像、新闻文章和视频相关的 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 方法

在此应用程序中,主方法包括实例化客户端的代码、验证 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

定义函数和筛选结果

现在,你已首次调用必应 Web 搜索 API,接下来让我们看看一些函数,这些函数突出显示了用于优化查询和筛选结果的 SDK 功能。 每个函数都可以添加到在上一节中创建的 C# 应用程序。

限制必应返回的结果数量

此示例使用 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. 运行应用程序。

清理资源

完成此项目后,请确保从应用程序的代码中删除订阅密钥。

后续步骤

使用必应 Web 搜索客户端库,可以轻松地将必应 Web 搜索集成到 Java 应用程序中。 在本快速入门中,你将了解如何发送请求、接收 JSON 响应以及筛选和分析结果。

想要立即查看代码? GitHub 上提供了适用于 Java 必应搜索客户端库的示例。

先决条件

在运行此快速入门之前,您需要准备以下事项:

创建 Azure 资源

通过创建以下 Azure 资源之一开始使用必应 Web 搜索 API:

必应搜索 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 方法

在此应用程序中,主方法包括实例化客户端的代码、验证 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

清理资源

完成此项目后,请确保从程序代码中删除订阅密钥。

后续步骤

另请参阅

使用必应 Web 搜索客户端库,可以轻松地将必应 Web 搜索集成到 Node.js 应用程序中。 在本快速入门中,你将了解如何实例化客户端、发送请求并打印响应。

想要立即查看代码? GitHub 上提供了适用于 JavaScript 必应搜索客户端库的示例。

先决条件

在运行此快速入门之前,您需要准备以下事项:

创建 Azure 资源

通过创建以下 Azure 资源之一开始使用必应 Web 搜索 API:

必应搜索 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);

发出请求并打印结果

使用客户端将搜索查询发送到必应 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;
})

运行程序

最后一步是运行程序!

清理资源

完成此项目后,请确保从程序代码中删除订阅密钥。

后续步骤

另请参阅

使用必应 Web 搜索客户端库,可以轻松地将必应 Web 搜索集成到 Python 应用程序中。 在本快速入门中,你将了解如何发送请求、接收 JSON 响应以及筛选和分析结果。

想要立即查看代码? GitHub 上提供了适用于 Python 必应搜索客户端库的示例。

先决条件

必应 Web 搜索 SDK 与 Python 2.7 或 3.6+ 兼容。 建议在本快速入门中使用虚拟环境。

  • Python 2.7 或 3.6+
  • 适用于 Python 2.7 的 virtualenv
  • 适用于 Python 3.x 的 venv

创建 Azure 资源

通过创建以下 Azure 资源之一开始使用必应 Web 搜索 API:

必应搜索 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

安装必应 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

安装必应 Web 搜索 SDK 依赖项:

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

创建客户端并打印第一个结果

设置虚拟环境和安装依赖项后,让我们创建一个客户端。 客户端将处理对必应 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

定义函数和筛选结果

现在,你已首次调用必应 Web 搜索 API,接下来让我们看看一些功能。 以下部分重点介绍了用于优化查询和筛选结果的 SDK 功能。 每个函数都可以添加到在上一部分创建的 Python 程序。

限制必应返回的结果数量

此示例使用 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 方法筛选搜索结果。 返回的搜索结果仅限于必应在过去 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. 运行程序。

请使用安全搜索、答案计数和推广筛选器

此示例使用 SDK promotesafe_searchsearch 参数筛选搜索结果。 第一个结果的 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. 运行程序。

清理资源

完成此项目后,请确保从程序代码中删除订阅密钥并停用虚拟环境。

后续步骤

另请参阅