Quickstart: Een Bing Web Search-clientbibliotheek gebruiken

Waarschuwing

Op 30 oktober 2020 zijn de Zoeken in Bing API's verplaatst van Azure AI-services naar Zoeken in Bing Services. Deze documentatie is alleen bedoeld ter referentie. Zie de bing-documentatie voor zoeken-API voor bijgewerkte documentatie. Zie Een Zoeken in Bing-resource maken via de Azure Marketplace voor instructies over het maken van nieuwe Azure-resources voor Bing Search.

Met de Bing Web Search-clientbibliotheek kunt u Bing Web Search eenvoudig integreren in uw C#-toepassing. In deze snelstartgids leert u hoe u een instantie maakt voor een client, een aanvraag verzendt en het antwoord weergeeft.

Wilt u de code nu zien? Voorbeelden voor de Bing Search-clientbibliotheken voor .NET zijn beschikbaar op GitHub.

Vereisten

Voordat u verdergaat met deze snelstart moet u beschikken over:

Een Azure-resource maken

Begin met het gebruik van de Bing Web Search-API door een van de volgende Azure-resources te maken:

Bing Search v7-resource

  • Beschikbaar via de Azure-portal totdat u de resource verwijdert.
  • Gebruik de gratis prijscategorie om de service uit te proberen, en voer later een upgrade uit naar een betaalde categorie voor productie.

Resource voor meerdere services

  • Beschikbaar via de Azure-portal totdat u de resource verwijdert.
  • Gebruik dezelfde sleutel en hetzelfde eindpunt voor uw toepassingen, in meerdere Azure AI-services.

Een project maken en afhankelijkheden installeren

Tip

Haal de nieuwste code als Visual Studio-oplossing op uit GitHub.

De eerste stap bestaat uit het maken van een nieuw consoleproject. Als u hulp nodig hebt bij het opzetten van een consoleproject, raadpleegt u Hello World: uw eerste programma (C#-programmeerhandleiding). Als u de Bing Web Search SDK wilt gebruiken in uw toepassing, moet u Microsoft.Azure.CognitiveServices.Search.WebSearch installeren met behulp van NuGet Package Manager.

Met het Web Search SDK-pakket wordt ook het volgende geïnstalleerd:

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

Afhankelijkheden declareren

Open uw project in Visual Studio of Visual Studio Code en importeer de volgende afhankelijkheden:

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;

Een projectopzet maken

Wanneer u het nieuwe consoleproject hebt gemaakt, moeten er een naamruimte en klasse voor uw toepassing zijn gemaakt. Uw programma moet eruitzien als dit voorbeeld:

namespace WebSearchSDK
{
    class YOUR_PROGRAM
    {

        // The code in the following sections goes here.

    }
}

In de volgende secties maken we onze voorbeeldtoepassing in deze klasse.

Een aanvraag samenstellen

Met deze code wordt de zoekquery samengesteld.

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

Het antwoord verwerken

Laten we vervolgens code toevoegen voor het parseren van het antwoord en het weergeven van de resultaten. De Name en Url voor de eerste webpagina, de eerste afbeelding, het eerste nieuwsartikel en de eerste video worden weergegeven wanneer ze voorkomen in het antwoordobject.

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

De hoofdmethode declareren

In deze toepassing bevat de hoofdmethode code waarmee een instantie wordt gemaakt voor de client, de subscriptionKey wordt gevalideerd en WebResults wordt aangeroepen. Zorg ervoor dat u een geldige abonnementssleutel voor uw Azure-account invoert voordat u verdergaat.

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

De toepassing uitvoeren

Nu gaan we de toepassing uitvoeren.

dotnet run

Functies definiëren en resultaten filteren

Nu u voor het eerst de Bing Webzoekopdrachten-API hebt aangeroepen, kunnen we enkele functies bekijken die een voorbeeld zijn van SDK-functionaliteit voor het verfijnen van query's en het filteren van resultaten. Elke functie kan worden toegevoegd aan uw C#-toepassing die in de vorige sectie is gemaakt.

Het aantal resultaten beperken dat door Bing wordt geretourneerd

In dit voorbeeld worden de parameters count en offset gebruikt voor het beperken van het aantal resultaten dat voor 'Beste restaurants in Seattle' wordt geretourneerd. De Name en Url voor het eerste resultaat worden weergegeven.

  1. Voeg deze code toe aan uw consoleproject:

    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. Voeg WebResultsWithCountAndOffset toe aan 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. Voer de toepassing uit.

Filteren op nieuws

In dit voorbeeld wordt de parameter response_filter gebruikt om zoekresultaten te filteren. De geretourneerde zoekresultaten zijn beperkt tot nieuwsartikelen voor 'Microsoft'. De Name en Url voor het eerste resultaat worden weergegeven.

  1. Voeg deze code toe aan uw consoleproject:

    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. Voeg WebResultsWithCountAndOffset toe aan 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. Voer de toepassing uit.

Gebruik de parameters voor veilig zoeken, aantal antwoorden en het filter voor het promoten van zoekresultaten

In dit voorbeeld worden de parameters answer_count, promote, en safe_search gebruikt om de zoekresultaten voor 'muziekvideo's' te filteren. De Name en ContentUrl voor het eerste resultaat worden weergegeven.

  1. Voeg deze code toe aan uw consoleproject:

    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. Voeg WebResultsWithCountAndOffset toe aan 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. Voer de toepassing uit.

Resources opschonen

Wanneer u klaar bent met dit project, moet u uw abonnementssleutel verwijderen uit de code van de toepassing.

Volgende stappen

Met de Bing Web Search-clientbibliotheek kunt u Bing Web Search eenvoudig integreren in uw Java-toepassing. In deze snelstartgids leert u hoe u een aanvraag verzendt, een JSON-antwoord ontvangt en de resultaten filtert en parseert.

Wilt u de code nu zien? Voorbeelden voor de Bing Search-clientbibliotheken voor Java zijn beschikbaar op GitHub.

Vereisten

Voordat u verdergaat met deze snelstart moet u beschikken over:

  • JDK 7 of 8
  • Apache Maven of uw favoriete hulpprogramma voor het automatiseren van builds
  • Een abonnementssleutel

Een Azure-resource maken

Begin met het gebruik van de Bing Web Search-API door een van de volgende Azure-resources te maken:

Bing Search v7-resource

  • Beschikbaar via de Azure-portal totdat u de resource verwijdert.
  • Gebruik de gratis prijscategorie om de service uit te proberen, en voer later een upgrade uit naar een betaalde categorie voor productie.

Resource voor meerdere services

  • Beschikbaar via de Azure-portal totdat u de resource verwijdert.
  • Gebruik dezelfde sleutel en hetzelfde eindpunt voor uw toepassingen, in meerdere Azure AI-services.

Een project maken en uw POM-bestand instellen

Maak een nieuw Java-project met behulp van Maven of uw favoriete hulpprogramma voor het automatiseren van builds. Ervan uitgaande dat u Maven gebruikt, moet u de volgende regels toevoegen aan het bestand Project Object Model (POM). Vervang alle instanties van mainClass door uw toepassing.

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

Afhankelijkheden declareren

Open uw project in uw favoriete IDE of editor en importeer de volgende afhankelijkheden:

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;

Als u het project hebt gemaakt met Maven, moet het pakket al zijn gedeclareerd. Als dat niet het geval is, moet u het pakket nu declareren. Bijvoorbeeld:

package com.bingwebsearch.app

De klasse BingWebSearchSample declareren

Declareer de klasse BingWebSearchSample. Deze zal het merendeel van onze code bevatten, inclusief de methode main.

public class BingWebSearchSample {

// The code in the following sections goes here.

}

Een aanvraag samenstellen

Met de methode runSample, die is opgenomen in de klasse BingWebSearchSample, wordt de aanvraag samengesteld. Kopieer de volgende code naar uw toepassing:

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

Het antwoord verwerken

Laten we vervolgens code toevoegen voor het parseren van het antwoord en het weergeven van de resultaten. De name en url voor de eerste webpagina, de eerste afbeelding, het eerste nieuwsartikel en de eerste video worden weergegeven wanneer ze zijn opgenomen in het antwoordobject.

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

De hoofdmethode declareren

In deze toepassing bevat de hoofdmethode code waarmee een instantie wordt gemaakt voor de client, de subscriptionKey wordt gevalideerd en runSample wordt aangeroepen. Zorg ervoor dat u een geldige abonnementssleutel voor uw Azure-account invoert voordat u verdergaat.

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

Het programma uitvoeren

Als laatste stap voert u het programma uit.

mvn compile exec:java

Resources opschonen

Wanneer u klaar bent met dit project, moet u uw abonnementssleutel verwijderen uit de code van het programma.

Volgende stappen

Zie ook

Met de Bing Web Search-clientbibliotheek kunt u Bing Web Search eenvoudig integreren in uw Node.js-toepassing. In deze snelstartgids leert u hoe u een instantie maakt voor een client, een aanvraag verzendt en het antwoord weergeeft.

Wilt u de code nu zien? Voorbeelden voor de Bing Search-clientbibliotheken voor JavaScript zijn beschikbaar op GitHub.

Vereisten

Voordat u verdergaat met deze snelstart moet u beschikken over:

Een Azure-resource maken

Begin met het gebruik van de Bing Web Search-API door een van de volgende Azure-resources te maken:

Bing Search v7-resource

  • Beschikbaar via de Azure-portal totdat u de resource verwijdert.
  • Gebruik de gratis prijscategorie om de service uit te proberen, en voer later een upgrade uit naar een betaalde categorie voor productie.

Resource voor meerdere services

  • Beschikbaar via de Azure-portal totdat u de resource verwijdert.
  • Gebruik dezelfde sleutel en hetzelfde eindpunt voor uw toepassingen, in meerdere Azure AI-services.

De ontwikkelomgeving instellen

U moet eerst de ontwikkelomgeving voor het Node.js-project opzetten.

  1. Maak een nieuwe map voor uw project:

    mkdir YOUR_PROJECT
    
  2. Maak een nieuw pakketbestand:

    cd YOUR_PROJECT
    npm init
    
  3. Nu gaan we enkele Azure-modules installeren en toevoegen aan de package.json:

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

Een project maken en de vereiste modules declareren

Maak in dezelfde map als uw package.json een nieuw Node.js-project met behulp van uw favoriete IDE of editor. Bijvoorbeeld: sample.js.

Vervolgens kopieert u deze code naar uw project. Hiermee worden de modules geladen die in de vorige sectie zijn geïnstalleerd.

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

Een instantie maken voor de client

Met deze code wordt een instantie gemaakt voor een client en wordt gebruikgemaakt van de module @azure/cognitiveservices-websearch. Zorg ervoor dat u een geldige abonnementssleutel voor uw Azure-account invoert voordat u verdergaat.

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

Een aanvraag maken en de resultaten weergeven

Gebruik de client om een zoekquery te verzenden naar Bing Web Search. Als het antwoord resultaten bevat voor items in de properties-matrix, wordt de result.value weergegeven in de console.

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

Het programma uitvoeren

Als laatste stap voert u het programma uit.

Resources opschonen

Wanneer u klaar bent met dit project, moet u uw abonnementssleutel verwijderen uit de code van het programma.

Volgende stappen

Zie ook

Met de Bing Web Search-clientbibliotheek kunt u Bing Web Search eenvoudig integreren in uw Python-toepassing. In deze snelstartgids leert u hoe u een aanvraag verzendt, een JSON-antwoord ontvangt en de resultaten filtert en parseert.

Wilt u de code nu zien? Voorbeelden voor de Bing Search-clientbibliotheken voor Python zijn beschikbaar op GitHub.

Vereisten

De Bing Web Search SDK is compatibel met Python 2.7 of 3.6+. We raden u aan om een virtuele omgeving te gebruiken voor deze snelstartgids.

Een Azure-resource maken

Begin met het gebruik van de Bing Web Search-API door een van de volgende Azure-resources te maken:

Bing Search v7-resource

  • Beschikbaar via de Azure-portal totdat u de resource verwijdert.
  • Gebruik de gratis prijscategorie om de service uit te proberen, en voer later een upgrade uit naar een betaalde categorie voor productie.

Resource voor meerdere services

  • Beschikbaar via de Azure-portal totdat u de resource verwijdert.
  • Gebruik dezelfde sleutel en hetzelfde eindpunt voor uw toepassingen, in meerdere Azure AI-services.

Uw virtuele omgeving maken en configureren

De instructies voor het opzetten en configureren van een virtuele omgeving zijn verschillend voor Python 2.x en Python 3.x. Voer de onderstaande stappen uit om uw virtuele omgeving te maken en te initialiseren.

Python 2.x

Maak een virtuele omgeving met virtualenv voor Python 2.7:

virtualenv mytestenv

Uw omgeving activeren:

cd mytestenv
source bin/activate

Installeer Bing Web Search SDK-afhankelijkheden:

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

Python 3.x

Maak een virtuele omgeving met venv voor Python 3.x:

python -m venv mytestenv

Uw omgeving activeren:

mytestenv\Scripts\activate.bat

Installeer Bing Web Search SDK-afhankelijkheden:

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

Een client maken en uw eerste resultaten weergeven

Nu u de virtuele omgeving hebt ingesteld en de afhankelijkheden hebt geïnstalleerd, kunnen we een client maken. De client verwerkt aanvragen voor en antwoorden afkomstig van de Bing Webzoekopdrachten-API.

Als het antwoord webpagina's, afbeeldingen, nieuws of video's bevat, wordt het eerste resultaat voor elk item weergegeven.

  1. Maak een nieuw Python-project met uw favoriete IDE of editor.

  2. Kopieer de volgende voorbeeldcode naar uw project. endpoint kan het volgende globale eindpunt zijn of het eindpunt aangepast subdomein dat wordt weergegeven in de Azure-portal voor uw resource.:

    # 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. Vervang SUBSCRIPTION_KEY door een geldige abonnementssleutel.

  4. Vervang YOUR_ENDPOINT door de eindpunt-URL in de portal en verwijder het gedeelte "bing/v7.0" uit het eindpunt.

  5. Voer het programma uit. Bijvoorbeeld: python your_program.py.

Functies definiëren en resultaten filteren

Nu u uw eerste aanroep hebt gedaan voor de Bing Web Search-API, gaan we eens een paar functies bekijken. De volgende secties gaan over de SDK-functionaliteit voor het verfijnen van query's en het filteren van resultaten. Deze functies kunnen worden toegevoegd aan uw Python-programma dat in de vorige sectie is gemaakt.

Het aantal resultaten beperken dat door Bing wordt geretourneerd

In dit voorbeeld worden de parameters count en offset gebruikt voor het beperken van het aantal resultaten dat wordt geretourneerd met de search-methode van de SDK. De name en url voor het eerste resultaat worden weergegeven.

  1. Voeg deze code toe aan uw Python-project:

     # 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. Voer het programma uit.

Filteren op nieuws en actuele items

In dit voorbeeld worden de parameters response_filter en freshness gebruikt om de zoekresultaten te filteren met de search-methode van de SDK. De geretourneerde zoekresultaten zijn beperkt tot nieuwsartikelen en pagina's die Bing heeft gedetecteerd gedurende de afgelopen 24 uur. De name en url voor het eerste resultaat worden weergegeven.

  1. Voeg deze code toe aan uw Python-project:

    # 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. Voer het programma uit.

Gebruik de parameters voor veilig zoeken, aantal antwoorden en het filter voor het promoten van zoekresultaten

In dit voorbeeld worden de parameters answer_count, promote en safe_search gebruikt om de zoekresultaten te filteren met de search-methode van de SDK. De name en url voor het eerste resultaat worden weergegeven.

  1. Voeg deze code toe aan uw Python-project:

    # 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. Voer het programma uit.

Resources opschonen

Wanneer u klaar bent met dit project, moet u uw abonnementssleutel verwijderen uit de code van het programma en uw virtuele omgeving deactiveren.

Volgende stappen

Zie ook