Mulai cepat: Menggunakan pustaka klien Bing Web Search

Peringatan

Pada 30 Oktober 2020, API Bing Search dipindahkan dari layanan Azure AI ke Bing Search Services. Dokumentasi ini disediakan hanya untuk referensi. Untuk dokumentasi terbaru, lihat dokumentasi Bing Search API. Untuk petunjuk tentang cara membuat sumber daya Azure baru untuk pencarian Bing, lihat Membuat sumber daya Pencarian Bing melalui Marketplace Azure.

Pustaka klien Bing Web Search memudahkan integrasi Bing Web Search ke dalam aplikasi C# Anda. Dalam mulai cepat ini, Anda akan mempelajari cara membuat instans klien, mengirim permintaan, dan mencetak respons.

Ingin melihat kodenya sekarang? Sampel untuk pustaka klien Bing Search untuk .NET tersedia di GitHub.

Prasyarat

Berikut adalah beberapa hal yang akan Anda butuhkan sebelum menjalankan mulai cepat ini:

Membuat grup sumber daya Azure

Mulai gunakan Bing Web Search API dengan membuat salah satu sumber daya Azure berikut:

Sumber daya Bing Search v7

  • Tersedia melalui portal Microsoft Azure hingga Anda menghapus sumber daya.
  • Gunakan tingkat harga gratis untuk mencoba layanan, dan tingkatkan ke tingkat berbayar untuk produksi di kemudian hari.

Sumber daya multilayanan

  • Tersedia melalui portal Microsoft Azure hingga Anda menghapus sumber daya.
  • Gunakan kunci dan titik akhir yang sama untuk aplikasi Anda, di beberapa layanan Azure AI.

Membuat proyek dan memasang dependensi

Tip

Dapatkan kode terbaru sebagai solusi Visual Studio dari GitHub.

Langkah pertama adalah membuat proyek konsol baru. Jika Anda memerlukan bantuan dalam mengatur proyek konsol, lihat Halo Dunia -- Program Pertama Anda (Panduan Pemrograman C# ). Untuk menggunakan Bing Web Search SDK di aplikasi, Anda harus memasang Microsoft.Azure.CognitiveServices.Search.WebSearch menggunakan Manajer Paket NuGet.

Paket SDK Pencarian Web juga memasang:

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

Menyatakan dependensi

Buka proyek Anda di Visual Studio atau Visual Studio Code dan impor dependensi berikut:

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;

Membuat perancah proyek

Saat Anda membuat proyek konsol baru, namespace layanan dan kelas untuk aplikasi Anda seharusnya dibuat. Program Anda akan terlihat seperti contoh ini:

namespace WebSearchSDK
{
    class YOUR_PROGRAM
    {

        // The code in the following sections goes here.

    }
}

Di bagian berikut, kami akan membuat aplikasi sampel dalam kelas ini.

Membuat permintaan

Kode ini membuat kueri pencarian.

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

Menangani respons

Selanjutnya, mari kita tambahkan beberapa kode untuk mengurai respons dan mencetak hasilnya. Name dan Url untuk halaman web pertama, gambar, artikel berita, dan video dicetak jika ada di objek respons.

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

Menyatakan metode utama

Dalam aplikasi ini, metode utama mencakup kode yang membuat instans untuk instantiates, memvalidasi subscriptionKey, dan panggilan WebResults. Pastikan Anda memasukkan kunci langganan yang valid untuk akun Azure sebelum melanjutkan.

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

Menjalankan aplikasi

Mari kita jalankan aplikasinya!

dotnet run

Menentukan fungsi dan memfilter hasil

Sekarang setelah Anda melakukan panggilan pertama ke Bing Web Search API, mari kita lihat beberapa fungsi yang menyoroti fungsionalitas SDK untuk menyempurnakan kueri dan memfilter hasil. Setiap fungsi dapat ditambahkan ke aplikasi C# yang dibuat di bagian sebelumnya.

Membatasi jumlah hasil yang dikembalikan oleh Bing

Sampel ini menggunakan parameter count dan offset untuk membatasi jumlah hasil yang dikembalikan untuk "Restoran terbaik di Seattle". Name dan Url untuk hasil pertama dicetak.

  1. Tambahkan kode ini ke proyek konsol Anda:

    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. Tambahkan WebResultsWithCountAndOffset ke 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. Jalankan aplikasi.

Filter untuk berita

Sampel ini menggunakan parameter response_filter untuk memfilter hasil pencarian. Hasil pencarian yang dikembalikan terbatas pada artikel berita untuk "Microsoft". Name dan Url untuk hasil pertama dicetak.

  1. Tambahkan kode ini ke proyek konsol Anda:

    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. Tambahkan WebResultsWithCountAndOffset ke 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. Jalankan aplikasi.

Menggunakan pencarian aman, jumlah jawaban, dan filter promosi

Contoh ini menggunakan parameter answer_count, promote, dan safe_search untuk memfilter hasil pencarian untuk "Video Musik". Name dan ContentUrl untuk hasil pertama ditampilkan.

  1. Tambahkan kode ini ke proyek konsol Anda:

    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. Tambahkan WebResultsWithCountAndOffset ke 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. Jalankan aplikasi.

Membersihkan sumber daya

Setelah selesai dengan proyek ini, pastikan untuk menghapus kunci langganan Anda dari kode aplikasi.

Langkah berikutnya

Pustaka klien Bing Web Search memudahkan integrasi Bing Web Search ke aplikasi Java Anda. Dalam mulai cepat ini, Anda akan mempelajari cara mengirim permintaan, menerima respons JSON, serta memfilter dan mengurai hasilnya.

Ingin melihat kodenya sekarang? Sampel untuk pustaka klien Bing Search untuk Java tersedia di GitHub.

Prasyarat

Berikut adalah beberapa hal yang akan Anda butuhkan sebelum menjalankan mulai cepat ini:

Membuat grup sumber daya Azure

Mulai gunakan Bing Web Search API dengan membuat salah satu sumber daya Azure berikut:

Sumber daya Bing Search v7

  • Tersedia melalui portal Microsoft Azure hingga Anda menghapus sumber daya.
  • Gunakan tingkat harga gratis untuk mencoba layanan, dan tingkatkan ke tingkat berbayar untuk produksi di kemudian hari.

Sumber daya multilayanan

  • Tersedia melalui portal Microsoft Azure hingga Anda menghapus sumber daya.
  • Gunakan kunci dan titik akhir yang sama untuk aplikasi Anda, di beberapa layanan Azure AI.

Membuat proyek dan menyiapkan file POM Anda

Buat proyek Java baru menggunakan Maven atau alat otomatisasi build favorit Anda. Dengan asumsi Anda menggunakan Maven, tambahkan baris berikut ke file Model Objek Proyek (POM) Anda. Ganti semua instans mainClass dengan aplikasi Anda.

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

Menyatakan dependensi

Buka proyek Anda di IDE atau editor favorit Anda dan impor dependensi ini:

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;

Jika Anda membuat proyek dengan Maven, paket harus sudah dinyatakan. Jika tidak, nyatakan paketnya sekarang. Contohnya:

package com.bingwebsearch.app

Menyatakan kelas BingWebSearchSample

Nyatakan kelas BingWebSearchSample. Ini akan mencakup sebagian besar kode kami termasuk metode main.

public class BingWebSearchSample {

// The code in the following sections goes here.

}

Membuat permintaan

Metode runSample ini, yang berada di kelas BingWebSearchSample, membuat permintaan. Salin kode ini ke dalam aplikasi Anda:

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

Menangani respons

Selanjutnya, mari kita tambahkan beberapa kode untuk mengurai respons dan mencetak hasilnya. name dan url untuk halaman web pertama, gambar, artikel berita, dan video dicetak ketika disertakan dalam objek respons.

/*
* 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...");
}

Menyatakan metode utama

Dalam aplikasi ini, metode utama mencakup kode yang membuat instans untuk instantiates, memvalidasi subscriptionKey, dan panggilan runSample. Pastikan Anda memasukkan kunci langganan yang valid untuk akun Azure sebelum melanjutkan.

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

Menjalankan program

Langkah terakhir adalah menjalankan program Anda.

mvn compile exec:java

Membersihkan sumber daya

Setelah selesai dengan proyek ini, pastikan untuk menghapus kunci langganan dari kode program.

Langkah berikutnya

Lihat juga

Pustaka klien Bing Web Search memudahkan integrasi Bing Web Search ke dalam aplikasi Node.js Anda. Dalam mulai cepat ini, Anda akan mempelajari cara membuat instans klien, mengirim permintaan, dan mencetak respons.

Ingin melihat kodenya sekarang? Sampel untuk pustaka klien Bing Search untuk JavaScript tersedia di GitHub.

Prasyarat

Berikut adalah beberapa hal yang akan Anda butuhkan sebelum menjalankan mulai cepat ini:

  • Node.js 6 atau yang lebih baru
  • Kunci langganan

Membuat grup sumber daya Azure

Mulai gunakan Bing Web Search API dengan membuat salah satu sumber daya Azure berikut:

Sumber daya Bing Search v7

  • Tersedia melalui portal Microsoft Azure hingga Anda menghapus sumber daya.
  • Gunakan tingkat harga gratis untuk mencoba layanan, dan tingkatkan ke tingkat berbayar untuk produksi di kemudian hari.

Sumber daya multilayanan

  • Tersedia melalui portal Microsoft Azure hingga Anda menghapus sumber daya.
  • Gunakan kunci dan titik akhir yang sama untuk aplikasi Anda, di beberapa layanan Azure AI.

Menyiapkan lingkungan pengembangan Anda

Mari mulai dengan menyiapkan lingkungan pengembangan untuk proyek Node.js.

  1. Buat direktori baru untuk proyek Anda:

    mkdir YOUR_PROJECT
    
  2. Buat dile paket baru:

    cd YOUR_PROJECT
    npm init
    
  3. Sekarang, mari menginstal beberapa modul Azure dan menambahkannya ke package.json:

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

Membuat proyek dan mendeklarasikan modul yang diperlukan

Dalam direktori yang sama dengan package.json Anda, buat proyek Node.js menggunakan IDE atau editor favorit Anda. Contoh: sample.js.

Selanjutnya, salin kode ini ke dalam proyek Anda. Ini memuat modul yang diinstal di bagian sebelumnya.

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

Membuat instans klien

Kode ini membuat instans klien dan menggunakan modul @azure/cognitiveservices-websearch. Pastikan Anda memasukkan kunci langganan yang valid untuk akun Azure sebelum melanjutkan.

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

Membuat permintaan dan mencetak hasilnya

Gunakan klien untuk mengirim kueri pencarian ke Bing Web Search. Jika respons menyertakan hasil untuk salah satu item dalam array properties, result.value akan dicetak ke konsol.

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

Menjalankan program

Langkah terakhir adalah menjalankan program Anda.

Membersihkan sumber daya

Setelah selesai dengan proyek ini, pastikan untuk menghapus kunci langganan dari kode program.

Langkah berikutnya

Lihat juga

Pustaka klien Pencarian Web Bing memudahkan integrasi Pencarian Web Bing ke dalam aplikasi Python Anda. Dalam mulai cepat ini, Anda akan mempelajari cara mengirim permintaan, menerima respons JSON, serta memfilter dan mengurai hasilnya.

Ingin melihat kodenya sekarang? Sampel untuk pustaka klien Pencarian Bing untuk Python tersedia di GitHub.

Prasyarat

SDK Pencarian Web Bing kompatibel dengan Python 2.7 atau 3.6+. Sebaiknya gunakan lingkungan virtual untuk mulai cepat ini.

  • Python 2.7 atau 3.6+
  • virtualenv untuk Python 2.7
  • venv for Python 3.x

Membuat grup sumber daya Azure

Mulai gunakan Bing Web Search API dengan membuat salah satu sumber daya Azure berikut:

Sumber daya Bing Search v7

  • Tersedia melalui portal Microsoft Azure hingga Anda menghapus sumber daya.
  • Gunakan tingkat harga gratis untuk mencoba layanan, dan tingkatkan ke tingkat berbayar untuk produksi di kemudian hari.

Sumber daya multilayanan

  • Tersedia melalui portal Microsoft Azure hingga Anda menghapus sumber daya.
  • Gunakan kunci dan titik akhir yang sama untuk aplikasi Anda, di beberapa layanan Azure AI.

Membuat dan mengonfigurasi lingkungan virtual Anda

Instruksi untuk mengatur dan mengonfigurasi lingkungan virtual berbeda untuk Python 2.x dan Python 3.x. Ikuti langkah-langkah di bawah ini untuk membuat dan menginisialisasi lingkungan virtual Anda.

Python 2.x

Buat lingkungan virtual dengan virtualenv untuk Python 2.7:

virtualenv mytestenv

Aktifkan lingkungan Anda:

cd mytestenv
source bin/activate

Pasang dependensi SDK Pencarian Web Bing:

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

Python 3.x

Buat lingkungan virtual dengan venv untuk Python 3.x:

python -m venv mytestenv

Aktifkan lingkungan Anda:

mytestenv\Scripts\activate.bat

Pasang dependensi SDK Pencarian Web Bing:

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

Membuat klien dan mencetak hasil pertama Anda

Setelah menyiapkan lingkungan virtual dan memasang dependensi, mari buat klien. Klien akan menangani permintaan dan respons dari API Pencarian Web Bing.

Jika responsnya berisi halaman web, gambar, berita, atau video, hasil pertama untuk masing-masing respons dicetak.

  1. Buat proyek Python baru menggunakan IDE atau editor favorit Anda.

  2. Salin kode sampel ini ke dalam proyek Anda. endpoint dapat menjadi titik akhir global di bawah ini, atau titik akhir subdomain kustom yang ditampilkan di portal Azure untuk sumber daya Anda.:

    # 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. Ganti SUBSCRIPTION_KEY dengan kunci langganan yang valid.

  4. Ganti YOUR_ENDPOINT dengan url titik akhir Anda di portal dan hapus bagian "bing/v7.0" dari titik akhir.

  5. Jalankan program. Contohnya: python your_program.py.

Menentukan fungsi dan memfilter hasil

Sekarang setelah Anda melakukan panggilan pertama ke API Pencarian Web Bing, mari lihat beberapa fungsi. Bagian berikut ini menyoroti fungsionalitas SDK untuk menyempurnakan kueri dan memfilter hasil. Setiap fungsi dapat ditambahkan ke program Python yang Anda buat di bagian sebelumnya.

Membatasi jumlah hasil yang dikembalikan oleh Bing

Sampel ini menggunakan parameter count dan offset untuk membatasi jumlah hasil yang dikembalikan menggunakan metode search SDK. name dan url untuk hasil pertama dicetak.

  1. Tambahkan kode ini ke proyek Python Anda:

     # 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. Jalankan program.

Filter untuk berita dan kesegaran

Sampel ini menggunakan parameter response_filter dan freshness untuk memfilter hasil pencarian menggunakan metode search SDK. Hasil pencarian yang dikembalikan terbatas pada artikel berita dan halaman yang telah ditemukan Bing dalam 24 jam terakhir. name dan url untuk hasil pertama dicetak.

  1. Tambahkan kode ini ke proyek Python Anda:

    # 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. Jalankan program.

Menggunakan pencarian aman, jumlah jawaban, dan filter promosi

Sampel ini menggunakan parameteranswer_count, promote, dan safe_search untuk memfilter hasil pencarian menggunakan metodesearch SDK. name dan url untuk hasil pertama ditampilkan.

  1. Tambahkan kode ini ke proyek Python Anda:

    # 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. Jalankan program.

Membersihkan sumber daya

Setelah selesai dengan proyek ini, pastikan untuk menghapus kunci langganan anda dari kode program dan untuk menonaktifkan lingkungan virtual Anda.

Langkah berikutnya

Lihat juga