다음을 통해 공유


빠른 시작: Bing Web Search 클라이언트 라이브러리 사용

경고

2020년 10월 30일, Bing Search API는 Azure AI 서비스에서 Bing Search Services로 이동했습니다. 이 설명서는 참조용으로만 제공됩니다. 업데이트된 설명서는 Bing Search API 설명서참조하세요. Bing 검색을 위한 새 Azure 리소스를 만드는 방법에 대한 지침은 Azure Marketplace통해 Bing Search 리소스 만들기를 참조하세요.

Bing Web Search 클라이언트 라이브러리를 사용하면 Bing Web Search를 C# 애플리케이션에 쉽게 통합할 수 있습니다. 이 빠른 시작에서는 클라이언트를 인스턴스화하고, 요청을 보내고, 응답을 인쇄하는 방법을 알아봅니다.

지금 코드를 보고 싶으신가요? .NET 대한 Bing Search 클라이언트 라이브러리에 대한 샘플은 GitHub에서 사용할 수 있습니다.

필수 조건

이 빠른 시작을 실행하기 전에 필요한 몇 가지 사항은 다음과 같습니다.

Azure 리소스 만들기

다음 Azure 리소스 중 하나를 만들어 Bing Web Search API 사용을 시작합니다.

Bing Search v7 리소스

  • 리소스를 삭제할 때까지 Azure Portal을 통해 사용할 수 있습니다.
  • 무료 가격 책정 계층을 사용하여 서비스를 체험하고 나중에 프로덕션용 유료 계층으로 업그레이드합니다.

다중 서비스 리소스

  • 리소스를 삭제할 때까지 Azure Portal을 통해 사용할 수 있습니다.
  • 여러 Azure AI 서비스에서 애플리케이션에 동일한 키와 엔드포인트를 사용합니다.

프로젝트 만들기 및 종속성 설치

팁 (조언)

GitHubVisual Studio 솔루션으로 최신 코드를 가져옵니다.

첫 번째 단계는 새 콘솔 프로젝트를 만드는 것입니다. 콘솔 프로젝트 설정에 도움이 필요한 경우 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);
    }
}

응답 처리

다음으로, 응답을 구문 분석하고 결과를 출력하는 코드를 추가해 보겠습니다. 첫 번째 웹 페이지, 이미지, 뉴스 기사 및 비디오의 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

함수 정의 및 결과 필터링

이제 Bing Web Search 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. 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_count, promotesafe_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. 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 클라이언트 라이브러리를 사용하면 Bing Web Search를 Java 애플리케이션에 쉽게 통합할 수 있습니다. 이 빠른 시작에서는 요청을 보내고, JSON 응답을 수신하고, 결과를 필터링하고 구문 분석하는 방법을 알아봅니다.

지금 코드를 보고 싶으신가요? Java Bing Search 클라이언트 라이브러리에 대한 샘플은 GitHub에서 사용할 수 있습니다.

필수 조건

이 빠른 시작을 실행하기 전에 필요한 몇 가지 사항은 다음과 같습니다.

Azure 리소스 만들기

다음 Azure 리소스 중 하나를 만들어 Bing Web Search API 사용을 시작합니다.

Bing Search v7 리소스

  • 리소스를 삭제할 때까지 Azure Portal을 통해 사용할 수 있습니다.
  • 무료 가격 책정 계층을 사용하여 서비스를 체험하고 나중에 프로덕션용 유료 계층으로 업그레이드합니다.

다중 서비스 리소스

  • 리소스를 삭제할 때까지 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.

}

요청 생성

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

리소스 정리

이 프로젝트를 완료하면 프로그램 코드에서 구독 키를 제거해야 합니다.

다음 단계

참고하십시오

Bing Web Search 클라이언트 라이브러리를 사용하면 Bing Web Search를 Node.js 애플리케이션에 쉽게 통합할 수 있습니다. 이 빠른 시작에서는 클라이언트를 인스턴스화하고, 요청을 보내고, 응답을 인쇄하는 방법을 알아봅니다.

지금 코드를 보고 싶으신가요? JavaScript Bing Search 클라이언트 라이브러리에 대한 샘플은 GitHub에서 사용할 수 있습니다.

필수 조건

이 빠른 시작을 실행하기 전에 필요한 몇 가지 사항은 다음과 같습니다.

Azure 리소스 만들기

다음 Azure 리소스 중 하나를 만들어 Bing Web Search API 사용을 시작합니다.

Bing Search v7 리소스

  • 리소스를 삭제할 때까지 Azure Portal을 통해 사용할 수 있습니다.
  • 무료 가격 책정 계층을 사용하여 서비스를 체험하고 나중에 프로덕션용 유료 계층으로 업그레이드합니다.

다중 서비스 리소스

  • 리소스를 삭제할 때까지 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 클라이언트 라이브러리를 사용하면 Bing Web Search를 Python 애플리케이션에 쉽게 통합할 수 있습니다. 이 빠른 시작에서는 요청을 보내고, 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을 통해 사용할 수 있습니다.
  • 무료 가격 책정 계층을 사용하여 서비스를 체험하고 나중에 프로덕션용 유료 계층으로 업그레이드합니다.

다중 서비스 리소스

  • 리소스를 삭제할 때까지 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의 요청 및 응답을 처리합니다.

응답에 웹 페이지, 이미지, 뉴스 또는 비디오가 포함된 경우 각각에 대한 첫 번째 결과가 인쇄됩니다.

  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에서 반환하는 결과 수 제한

이 샘플에서는 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_count, promotesafe_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. 프로그램을 실행합니다.

리소스 정리

이 프로젝트를 완료하면 프로그램의 코드에서 구독 키를 제거하고 가상 환경을 비활성화해야 합니다.

다음 단계

참고하십시오