Hızlı Başlangıç: Bing Web Araması istemci kitaplığı kullanma

Uyarı

30 Ekim 2020'de Bing Arama API'leri Azure yapay zeka hizmetlerinden Bing Arama Hizmetlerine taşındı. Bu belgeler yalnızca başvuru için sağlanır. Güncelleştirilmiş belgeler için Bing arama API'sinin belgelerine bakın. Bing araması için yeni Azure kaynakları oluşturma yönergeleri için bkz. Azure Market aracılığıyla Bing Arama kaynağı oluşturma.

Bing Web Araması istemci kitaplığı, Bing Web Araması'nı C# uygulamanızla tümleştirmeyi kolaylaştırır. Bu hızlı başlangıçta istemci başlatmayı, istek göndermeyi ve yanıtı yazdırmayı öğreneceksiniz.

Kodu hemen görmek istiyor musunuz? .NET için Bing Arama istemci kitaplıklarına yönelik örnekler GitHub'da bulunabilir.

Önkoşullar

Bu hızlı başlangıcı çalıştırmak için aşağıdakilere ihtiyacınız olacaktır:

Azure kaynağı oluşturma

Aşağıdaki Azure kaynaklarından birini oluşturarak Bing Web Araması API'sini kullanmaya başlayın:

Bing Arama v7 kaynağı

  • Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
  • Hizmeti denemek için ücretsiz fiyatlandırma katmanını kullanın ve daha sonra üretim için ücretli bir katmana yükseltin.

Çok hizmetli kaynak

  • Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
  • Birden çok Azure AI hizmeti genelinde uygulamalarınız için aynı anahtarı ve uç noktayı kullanın.

Proje oluşturma ve bağımlılıkları yükleme

İpucu

GitHub'dan Visual Studio çözümü olarak en son kodu alın.

İlk adım yeni bir konsol projesi oluşturmaktır. Konsol projesi ayarlama konusunda yardıma ihtiyacınız varsa bkz. Merhaba Dünya -- İlk Programınız (C# Programlama Kılavuzu). Bing Web Araması SDK'sını uygulamanızda kullanmak için NuGet Paket Yöneticisi'ni kullanarak Microsoft.Azure.CognitiveServices.Search.WebSearch paketini yüklemeniz gerekir.

Web Arama SDK'sı paketi şunları da yükler:

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

Bağımlılıkları tanımlama

Projenizi Visual Studio veya Visual Studio Code ile açıp şu bağımlılıkları içeri aktarın:

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;

Proje yapı iskelesini oluşturma

Yeni konsol projenizi oluşturduğunuzda uygulamanız için bir ad alanı ve sınıf da oluşturulmuş olmalıdır. Programınız şu örnekteki gibi görünmelidir:

namespace WebSearchSDK
{
    class YOUR_PROGRAM
    {

        // The code in the following sections goes here.

    }
}

Aşağıdaki bölümlerde örnek uygulamamızı bu sınıfı kullanarak derleyeceğiz.

İstek oluşturma

Bu kod, arama sorgusunu oluşturur.

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

Yanıtı işleme

Şimdi yanıtı ayrıştırmak ve sonuçları yazdırmak için kod ekleyelim. Yanıt nesnesinde mevcutsa ilk web sayfası, görüntü, haber ve video için Name ile Url değeri yazdırılır.

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 metodunu tanımlama

Bu uygulamada main metodu istemciyi başlatan, subscriptionKey değerini doğrulayan ve WebResults çağrısı yapan kodu içerir. Devam etmeden önce Azure hesabınız için geçerli bir abonelik anahtarı girdiğinizden emin olun.

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

Uygulamayı çalıştırma

Şimdi uygulamayı çalıştıralım!

dotnet run

İşlevleri tanımlama ve sonuçları filtreleme

Bing Web Araması API'sine ilk çağrınızı gönderdiniz. Şimdi sorguları daha ayrıntılı hale getirmek ve sonuçları filtrelemek için kullanabileceğiniz SDK işlevlerine göz atalım. Tüm işlevleri önceki bölümde oluşturulan C# uygulamanıza ekleyebilirsiniz.

Bing tarafından döndürülen sonuç sayısını sınırlama

Bu örnekte "Best restaurants in Seattle" (Seattle'daki en iyi restoranlar) araması için döndürülen sonuçları sınırlandırmak için count ve offset parametreleri kullanılmıştır. İlk sonucun Name ve Url değerleri yazdırılır.

  1. Konsol projenize şu kodu ekleyin:

    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. main içine WebResultsWithCountAndOffset ekleyin:

    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. Uygulamayı çalıştırın.

Haberler için filtre

Bu örnekte arama sonuçlarını filtrelemek için response_filter parametresi kullanılmıştır. Döndürülen arama sonuçları "Microsoft" haberleriyle sınırlandırılmıştır. İlk sonucun Name ve Url değerleri yazdırılır.

  1. Konsol projenize şu kodu ekleyin:

    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. main içine WebResultsWithCountAndOffset ekleyin:

    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. Uygulamayı çalıştırın.

Güvenli arama, yanıt sayısı ve yükseltme filtresini kullanma

Bu örnekte "Music Videos" (Müzik Videoları) aramasının sonuçlarını filtrelemek için answer_count, promote ve safe_search parametreleri kullanılmıştır. İlk sonucun Name ve ContentUrl değerleri görüntülenir.

  1. Konsol projenize şu kodu ekleyin:

    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. main içine WebResultsWithCountAndOffset ekleyin:

    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. Uygulamayı çalıştırın.

Kaynakları temizleme

Bu projeyi tamamladıktan sonra abonelik anahtarınızı uygulama kodundan kaldırmayı unutmayın.

Sonraki adımlar

Bing Web Araması istemci kitaplığı, Bing Web Araması'nı Java uygulamanızla tümleştirmeyi kolaylaştırır. Bu hızlı başlangıçta istek göndermeyi, JSON yanıtı almayı, sonuçları filtrelemeyi ve ayrıştırmayı öğreneceksiniz.

Kodu hemen görmek istiyor musunuz? Java için Bing Arama istemci kitaplıklarına yönelik örnekler GitHub'da sağlanır.

Önkoşullar

Bu hızlı başlangıcı çalıştırmak için aşağıdakilere ihtiyacınız olacaktır:

Azure kaynağı oluşturma

Aşağıdaki Azure kaynaklarından birini oluşturarak Bing Web Araması API'sini kullanmaya başlayın:

Bing Arama v7 kaynağı

  • Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
  • Hizmeti denemek için ücretsiz fiyatlandırma katmanını kullanın ve daha sonra üretim için ücretli bir katmana yükseltin.

Çok hizmetli kaynak

  • Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
  • Birden çok Azure AI hizmeti genelinde uygulamalarınız için aynı anahtarı ve uç noktayı kullanın.

Proje oluşturma ve POM dosyanızı ayarlama

Maven veya favori derleme otomasyonu aracınızı kullanarak yeni bir Java projesi oluşturun. Maven kullandığınızı varsayarsak, Proje Nesne Modeli (POM) dosyanıza aşağıdaki satırları ekleyin. mainClass yerine uygulamanızı yazın.

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

Bağımlılıkları tanımlama

Projenizi favori IDE ortamınızda veya düzenleyicide açıp şu bağımlılıkları içeri aktarın:

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;

Projeyi Maven ile oluşturduysanız paketin tanımlanmış olması gerekir. Aksi takdirde paketi bu adımda tamamlayın. Örnek:

package com.bingwebsearch.app

BingWebSearchSample sınıfını tanımlama

BingWebSearchSample sınıfını tanımlayın. main metodu dahil olmak üzere kodumuzun çoğunu içerecek.

public class BingWebSearchSample {

// The code in the following sections goes here.

}

İstek oluşturma

BingWebSearchSample sınıfında bulunan runSample metodu, isteği oluşturur. Şu kodu uygulamanıza kopyalayın:

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

Yanıtı işleme

Şimdi yanıtı ayrıştırmak ve sonuçları yazdırmak için kod ekleyelim. Yanıt nesnesine eklendiğinde ilk web sayfası, görüntü, haber ve video için name ile url değeri yazdırılır.

/*
* 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 metodunu tanımlama

Bu uygulamada main metodu istemciyi başlatan, subscriptionKey değerini doğrulayan ve runSample çağrısı yapan kodu içerir. Devam etmeden önce Azure hesabınız için geçerli bir abonelik anahtarı girdiğinizden emin olun.

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

Programı çalıştırma

Son adım programınızı çalıştırmaktır!

mvn compile exec:java

Kaynakları temizleme

Bu projeyi tamamladıktan sonra abonelik anahtarınızı program kodundan kaldırmayı unutmayın.

Sonraki adımlar

Ayrıca bkz.

Bing Web Araması istemci kitaplığı, Bing Web Araması'nı Node.js uygulamanızla tümleştirmeyi kolaylaştırır. Bu hızlı başlangıçta istemci başlatmayı, istek göndermeyi ve yanıtı yazdırmayı öğreneceksiniz.

Kodu hemen görmek istiyor musunuz? JavaScript için Bing Arama istemci kitaplıklarına yönelik örnekler GitHub'da bulunabilir.

Önkoşullar

Bu hızlı başlangıcı çalıştırmak için aşağıdakilere ihtiyacınız olacaktır:

Azure kaynağı oluşturma

Aşağıdaki Azure kaynaklarından birini oluşturarak Bing Web Araması API'sini kullanmaya başlayın:

v7 kaynağını Bing Arama

  • Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
  • Hizmeti denemek için ücretsiz fiyatlandırma katmanını kullanın ve daha sonra üretim için ücretli bir katmana yükseltin.

Çok hizmetli kaynak

  • Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
  • Birden çok Azure AI hizmeti genelinde uygulamalarınız için aynı anahtarı ve uç noktayı kullanın.

Geliştirme ortamınızı kurma

Node.js projemiz için geliştirme ortamını ayarlayarak başlayalım.

  1. Projeniz için yeni bir dizin oluşturun:

    mkdir YOUR_PROJECT
    
  2. Yeni bir paket dosyası oluşturun:

    cd YOUR_PROJECT
    npm init
    
  3. Şimdi bazı Azure modüllerini yükleyip öğesine ekleyelim package.json:

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

Bir proje oluşturun ve gerekli modülleri bildirin

package.json ile aynı dizinde favori IDE ortamınızı veya düzenleyiciyi kullanarak yeni bir Node.js projesi oluşturun. Örneğin: sample.js.

Şimdi bu kodu projenize kopyalayın. Önceki bölümde yüklenen modülleri yükler.

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

İstemciyi başlatma

Bu kod @azure/cognitiveservices-websearch modünü kullanarak bir istemci başlatır. Devam etmeden önce Azure hesabınız için geçerli bir abonelik anahtarı girdiğinizden emin olun.

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

İstekte bulunma ve sonuçları yazdırma

İstemciyi kullanarak Bing Web Araması'na bir arama sorgusu gönderin. Yanıt properties dizisindeki öğeler için sonuç içerirse konsolda result.value yazılır.

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

Programı çalıştırma

Son adım programınızı çalıştırmaktır!

Kaynakları temizleme

Bu projeyi tamamladıktan sonra abonelik anahtarınızı program kodundan kaldırmayı unutmayın.

Sonraki adımlar

Ayrıca bkz.

Bing Web Araması istemci kitaplığı, Bing Web Araması'nı Python uygulamanızla tümleştirmeyi kolaylaştırır. Bu hızlı başlangıçta istek göndermeyi, JSON yanıtı almayı, sonuçları filtrelemeyi ve ayrıştırmayı öğreneceksiniz.

Kodu hemen görmek istiyor musunuz? Python için Bing Arama istemci kitaplıklarına yönelik örnekler GitHub'da bulunabilir.

Önkoşullar

Bing Web Araması SDK'sı Python 2.7 veya 3.6+ ile uyumludur. Bu hızlı başlangıç için sanal ortam kullanmanızı öneririz.

  • Python 2.7 veya 3.6+
  • Python 2.7 için virtualenv
  • Python 3.x için venv

Azure kaynağı oluşturma

Aşağıdaki Azure kaynaklarından birini oluşturarak Bing Web Araması API'sini kullanmaya başlayın:

v7 kaynağını Bing Arama

  • Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
  • Hizmeti denemek için ücretsiz fiyatlandırma katmanını kullanın ve daha sonra üretim için ücretli bir katmana yükseltin.

Çok hizmetli kaynak

  • Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
  • Birden çok Azure AI hizmeti genelinde uygulamalarınız için aynı anahtarı ve uç noktayı kullanın.

Sanal ortamınızı oluşturma ve yapılandırma

Sanal ortamınızı ayarlama ve yapılandırma talimatları Python 2.x ve Python 3.x sürümleri için değişiklik gösterecektir. Sanal ortamınızı oluşturmak ve başlatmak için aşağıdaki adımları izleyin.

Python 2.x

Python 2.7 için virtualenv ile sanal ortam oluşturun:

virtualenv mytestenv

Ortamınızı etkinleştirme:

cd mytestenv
source bin/activate

Bing Web Araması SDK'sı bağımlılıklarını yükleyin:

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

Python 3.x

Python 3.x için venv ile sanal ortam oluşturun:

python -m venv mytestenv

Ortamınızı etkinleştirme:

mytestenv\Scripts\activate.bat

Bing Web Araması SDK'sı bağımlılıklarını yükleyin:

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

İstemci oluşturma ve ilk sonuçlarınızı yazdırma

Sanal ortamınızı ayarladığınıza ve bağımlılıkları yüklediğinizde göre bir istemci oluşturabilirsiniz. İstemci, Bing Web Araması API'sinden gelen istekleri ve yanıtları işler.

Yanıtta web sayfaları, görüntüler, haberler veya videolar varsa hepsinin ilk sonuçları yazdırılır.

  1. Favori IDE ortamınızda veya düzenleyicide yeni bir Python projesi oluşturun.

  2. Bu örnek kodu projenize kopyalayın. endpointaşağıdaki genel uç nokta veya kaynağınızın Azure portal görüntülenen özel alt etki alanı uç noktası olabilir:

    # 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 değerini geçerli bir abonelik anahtarıyla değiştirin.

  4. değerini portalda uç nokta URL'nizle değiştirin YOUR_ENDPOINT ve uç noktadan "bing/v7.0" bölümünü kaldırın.

  5. Programı çalıştırın. Örneğin: python your_program.py.

İşlevleri tanımlama ve sonuçları filtreleme

Bing Web Araması API'sine ilk çağrınızı yaptığınıza göre şimdi birkaç işleve göz atalım. Aşağıdaki bölümlerde sorguları iyileştirmeye ve sonuçları filtrelemeye yönelik SDK işlevselliği vurgulanmıştır. Her işlev, önceki bölümde oluşturduğunuz Python programına eklenebilir.

Bing tarafından döndürülen sonuç sayısını sınırlama

Bu örnek, SDK'nınsearchcount yöntemini kullanarak döndürülen sonuç sayısını sınırlamak için ve offset parametrelerini kullanır. İlk sonucun name ve url değerleri yazdırılır.

  1. Python projenize şu kodu ekleyin:

     # 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. Programı çalıştırın.

Haberler ve güncellik filtresi

Bu örnek, SDK'nınsearch yöntemini kullanarak arama sonuçlarını filtrelemek için ve freshness parametrelerini kullanırresponse_filter. Döndürülen arama sonuçları Bing'in son 24 saat içinde keşfettiği haberler ve sayfalarla sınırlıdır. İlk sonucun name ve url değerleri yazdırılır.

  1. Python projenize şu kodu ekleyin:

    # 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. Programı çalıştırın.

Güvenli arama, yanıt sayısı ve yükseltme filtresini kullanma

Bu örnek, SDK'nınsearchanswer_count yöntemini kullanarak arama sonuçlarını filtrelemek için , promoteve safe_search parametrelerini kullanır. İlk sonucun name ve url değerleri görüntülenir.

  1. Python projenize şu kodu ekleyin:

    # 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. Programı çalıştırın.

Kaynakları temizleme

Bu projeyi tamamladıktan sonra abonelik anahtarınızı program kodundan kaldırmayı ve sanal ortamınızı devre dışı bırakmayı unutmayın.

Sonraki adımlar

Ayrıca bkz.