Snabbstart: Använda ett klientbibliotek för webbsökning i Bing
Varning
Den 30 oktober 2020 flyttade Bing-sökning API:er från Azure AI-tjänster till Bing-sökning Services. Den här dokumentationen tillhandahålls endast som referens. Uppdaterad dokumentation finns i dokumentationen för API:et för Bing-sökning. Anvisningar om hur du skapar nya Azure-resurser för Bing-sökning finns i Skapa en Bing-sökning resurs via Azure Marketplace.
Klientbiblioteket för webbsökning i Bing gör det enkelt att integrera Bing Web Search i C#-programmet. I den här snabbstarten lär du dig att instansiera en klient, skicka en begäran och skriva ut svaret.
Vill du se koden på en gång? Exempel för Bing-sökning klientbibliotek för .NET finns på GitHub.
Förutsättningar
Här följer några saker som du behöver innan du kör den här snabbstarten:
Skapa en Azure-resurs
Börja använda API:et för webbsökning i Bing genom att skapa någon av följande Azure-resurser:
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd den kostnadsfria prisnivån för att prova tjänsten och uppgradera senare till en betald nivå för produktion.
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd samma nyckel och slutpunkt för dina program i flera Azure AI-tjänster.
Skapa ett projekt och installera beroenden
Tips
Hämta den senaste koden som en Visual Studio-lösning från GitHub.
Det första steget är att skapa ett nytt konsollprojekt. Om du behöver hjälp med att konfigurera ett konsolprojekt kan du läsa Hello World – Programmeringsguiden för ditt första program (C#). För att kunna använda API för webbsökning i Bing i ditt program behöver du installera Microsoft.Azure.CognitiveServices.Search.WebSearch
med hjälp av NuGet-pakethanteraren.
SDK-paketet för webbsökning installeras också:
- Microsoft.Rest.ClientRuntime
- Microsoft.Rest.ClientRuntime.Azure
- Newtonsoft.Json
Deklarera beroenden
Öppna projektet i Visual Studio eller i Visual Studio Code och importera dessa beroenden:
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;
Skapa projektställningar
När du skapade det nya konsolprojektet bör en namnrymd och en klass för programmet ha skapats. Programmet bör se ut så här:
namespace WebSearchSDK
{
class YOUR_PROGRAM
{
// The code in the following sections goes here.
}
}
I följande avsnitt bygger vi exempelprogrammet i den här klassen.
Skapa en begäran
Den här koden konstruerar sökfrågan.
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);
}
}
Hantera svaret
Nu lägger vi till kod för att parsa svaret och skriva ut resultatet.
Name
och Url
för den första webbplatsen, bilden, nyhetsartikeln och videon skrivs ut om de förekommer i svarsobjektet.
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...");
}
Deklarera main-metoden
I det här programmet innehåller main-metoden kod som instansierar klienten, verifierar subscriptionKey
och anropar WebResults
. Se till att du anger en giltig prenumerationsnyckel för ditt Azure-konto innan du fortsätter.
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();
}
Kör programmet
Nu kör vi programmet!
dotnet run
Definiera funktioner och filtrera resultat
Nu när du har gjort ditt första anrop till API för webbsökning i Bing tittar vi på några funktioner som demonstrerar SDK-funktionaliteten för att förfina frågor och filtrera resultaten. Varje funktion kan läggas till i ditt C#-program som skapades i föregående avsnitt.
Begränsa antalet resultat som returneras av Bing
I det här exemplet används parametrarna count
och offset
för att begränsa antalet resultat som returneras för "Best restaurants in Seattle" (bästa restaurangerna i Seattle).
Name
och Url
för det första resultatet skrivs ut.
Lägg till den här koden i konsolprojektet:
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); } }
Lägg till
WebResultsWithCountAndOffset
imain
: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(); }
Kör appen.
Filtrera efter nyheter
Det här exemplet används parametern response_filter
för att filtrera sökresultaten. De sökresultat som returneras är begränsade till nyhetsartiklar för "Microsoft".
Name
och Url
för det första resultatet skrivs ut.
Lägg till den här koden i konsolprojektet:
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); } }
Lägg till
WebResultsWithCountAndOffset
imain
: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(); }
Kör appen.
Använd säker sökning, svarsantal och befordringsfiltret
I det här exemplet används parametrarna answer_count
, promote
och safe_search
för att filtrera sökresultat för "Music Videos" (musikvideor).
Name
och ContentUrl
för det första resultatet visas.
Lägg till den här koden i konsolprojektet:
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); } }
Lägg till
WebResultsWithCountAndOffset
imain
: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(); }
Kör appen.
Rensa resurser
När du är klar med det här projektet bör du ta bort din prenumerationsnyckel från programmets kod.
Nästa steg
Klientbiblioteket för webbsökning i Bing gör det enkelt att integrera Bing Web Search i java-programmet. I den här snabbstarten lär du dig att skicka en begäran, ta emot ett JSON-svar och filtrera och parsa resultaten.
Vill du se koden på en gång? Exempel för Bing-sökning klientbibliotek för Java finns på GitHub.
Förutsättningar
Här följer några saker som du behöver innan du kör den här snabbstarten:
- JDK 7 eller 8
- Apache Maven eller valfritt verktyg för versionsautomatisering
- En prenumerationsnyckel
Skapa en Azure-resurs
Börja använda API:et för webbsökning i Bing genom att skapa någon av följande Azure-resurser:
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd den kostnadsfria prisnivån för att prova tjänsten och uppgradera senare till en betald nivå för produktion.
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd samma nyckel och slutpunkt för dina program i flera Azure AI-tjänster.
Skapa ett projekt och konfigurera POM-filen
Skapa ett nytt Java-projekt med hjälp av Maven eller valfritt verktyg för versionsautomatisering. Förutsatt att du använder Maven lägger du till följande rader i filen Project Object Model (POM). Ersätt alla förekomster av mainClass
med ditt program.
<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>
Deklarera beroenden
Öppna projektet i valfri IDE eller redigeringsprogram och importera dessa beroenden:
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;
Om du skapade projektet med Maven bör paketet redan vara deklarerat. Annars deklarerar du paketet nu. Exempel:
package com.bingwebsearch.app
Deklarera klassen BingWebSearchSample
Deklarera klassen BingWebSearchSample
. Den kommer att innehålla den största delen av vår kod, inklusive metoden main
.
public class BingWebSearchSample {
// The code in the following sections goes here.
}
Skapa en begäran
Metoden runSample
, som finns i klassen BingWebSearchSample
, konstruerar begäran. Kopiera den här koden till programmet:
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...
Hantera svaret
Nu lägger vi till kod för att parsa svaret och skriva ut resultatet.
name
och url
för den första webbplatsen, bilden, nyhetsartikeln och videon skrivs ut när de ingår i svarsobjektet.
/*
* 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...");
}
Deklarera main-metoden
I det här programmet innehåller main-metoden kod som instansierar klienten, verifierar subscriptionKey
och anropar runSample
. Se till att du anger en giltig prenumerationsnyckel för ditt Azure-konto innan du fortsätter.
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();
}
}
Köra programmet
Det sista steget är att köra programmet!
mvn compile exec:java
Rensa resurser
När du är klar med det här projektet bör du ta bort din prenumerationsnyckel från programmets kod.
Nästa steg
Se även
Klientbiblioteket för webbsökning i Bing gör det enkelt att integrera webbsökning i Bing i ditt Node.js program. I den här snabbstarten lär du dig att instansiera en klient, skicka en begäran och skriva ut svaret.
Vill du se koden på en gång? Exempel för Bing-sökning klientbibliotek för JavaScript finns på GitHub.
Förutsättningar
Här följer några saker som du behöver innan du kör den här snabbstarten:
- Node.js 6 eller senare
- En prenumerationsnyckel
Skapa en Azure-resurs
Börja använda API:et för webbsökning i Bing genom att skapa någon av följande Azure-resurser:
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd den kostnadsfria prisnivån för att prova tjänsten och uppgradera senare till en betald nivå för produktion.
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd samma nyckel och slutpunkt för dina program i flera Azure AI-tjänster.
Ställt in din utvecklingsmiljö
Vi börjar med att konfigurera utvecklingsmiljön för Node.js-projektet.
Skapa en ny katalog för projektet:
mkdir YOUR_PROJECT
Skapa en ny paketfil:
cd YOUR_PROJECT npm init
Nu ska vi installera några Azure-moduler och lägga till dem i
package.json
:npm install --save @azure/cognitiveservices-websearch npm install --save @azure/ms-rest-azure-js
Skapa ett projekt och deklarera nödvändiga moduler
I samma katalog som din package.json
skapar du ett nytt Node.js-projekt med hjälp av valfri IDE eller redigeringsprogram. Exempel: sample.js
.
Kopiera den här koden till projektet. Den läser in de moduler som installerades i föregående avsnitt.
const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
const WebSearchAPIClient = require('@azure/cognitiveservices-websearch');
Instansiera klienten
Den här koden instansierar en klient och använder modulen @azure/cognitiveservices-websearch
. Se till att du anger en giltig prenumerationsnyckel för ditt Azure-konto innan du fortsätter.
let credentials = new CognitiveServicesCredentials('YOUR-ACCESS-KEY');
let webSearchApiClient = new WebSearchAPIClient(credentials);
Göra en begäran och skriva ut resultatet
Använd klienten för att skicka en sökfråga till Webbsökning i Bing. Om svaret innehåller resultat för något av objekten properties
-matrisen skrivs result.value
ut till konsolen.
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;
})
Köra programmet
Det sista steget är att köra programmet!
Rensa resurser
När du är klar med det här projektet bör du ta bort din prenumerationsnyckel från programmets kod.
Nästa steg
Se även
Klientbiblioteket för webbsökning i Bing gör det enkelt att integrera webbsökning i Bing i Python-programmet. I den här snabbstarten lär du dig att skicka en begäran, ta emot ett JSON-svar och filtrera och parsa resultaten.
Vill du se koden på en gång? Exempel för Bing-sökning klientbibliotek för Python finns på GitHub.
Förutsättningar
SDK:n för webbsökning i Bing är kompatibel med Python 2.7 eller 3.6+. Vi rekommenderar att du använder en virtuell miljö för den här snabbstarten.
- Python 2.7 eller 3.6+
- virtualenv för Python 2.7
- venv för Python 3.x
Skapa en Azure-resurs
Börja använda API:et för webbsökning i Bing genom att skapa någon av följande Azure-resurser:
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd den kostnadsfria prisnivån för att prova tjänsten och uppgradera senare till en betald nivå för produktion.
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd samma nyckel och slutpunkt för dina program i flera Azure AI-tjänster.
Skapa och konfigurera den virtuella miljön
Anvisningarna för att installera och konfigurera en virtuell miljö är olika för Python 2.x och Python 3.x. Följ stegen nedan för att skapa och initiera den virtuella miljön.
Python 2.x
Skapa en virtuell miljö med virtualenv
för Python 2.7:
virtualenv mytestenv
Aktivera miljön:
cd mytestenv
source bin/activate
Installera beroenden för SDK för Webbsökning i Bing:
python -m pip install azure-cognitiveservices-search-websearch
Python 3.x
Skapa en virtuell miljö med venv
för Python 3.x:
python -m venv mytestenv
Aktivera miljön:
mytestenv\Scripts\activate.bat
Installera beroenden för SDK för Webbsökning i Bing:
cd mytestenv
python -m pip install azure-cognitiveservices-search-websearch
Skapa en klient och skriva ut dina första resultat
Nu när du har konfigurerat den virtuella miljön och installerat beroenden tar vi och skapar en klient. Klienten hanterar begäranden till och svar från API för webbsökning i Bing.
Om svaret innehåller webbplatser, bilder, nyheter eller videor skrivs det första resultatet för vardera ut.
Skapa ett nytt Python-projekt med valfri IDE eller redigeringsprogram.
Kopiera den här exempelkoden till projektet.
endpoint
kan vara den globala slutpunkten nedan eller den anpassade underdomänslutpunkten som visas i Azure Portal för resursen.:# 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...")
Ersätt
SUBSCRIPTION_KEY
med en giltig prenumerationsnyckel.Ersätt
YOUR_ENDPOINT
med slutpunkts-URL:en i portalen och ta bort avsnittet "bing/v7.0" från slutpunkten.Kör programmet. Exempel:
python your_program.py
.
Definiera funktioner och filtrera resultat
Nu när du har gjort ditt första anrop till API:et för webbsökning i Bing ska vi titta på några funktioner. I följande avsnitt beskrivs SDK-funktioner för att förfina frågor och filtrera resultat. Varje funktion kan läggas till i Python-programmet som du skapade i föregående avsnitt.
Begränsa antalet resultat som returneras av Bing
Det här exemplet använder parametrarna count
och offset
för att begränsa antalet resultat som returneras med hjälp av SDK-metodensearch
.
name
och url
för det första resultatet skrivs ut.
Lägg till den här koden i Python-projektet:
# 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))
Kör programmet.
Filtrera efter nyheter och aktualitet
Det här exemplet använder parametrarna response_filter
och freshness
för att filtrera sökresultat med hjälp av SDK-metodensearch
. De sökresultat som returneras är begränsade till nyhetsartiklar och sidor som Bing har identifierat under de senaste 24 timmarna.
name
och url
för det första resultatet skrivs ut.
Lägg till den här koden i Python-projektet:
# 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)
Kör programmet.
Använd säker sökning, svarsantal och befordringsfiltret
I det här exemplet används parametrarna answer_count
, promote
och safe_search
för att filtrera sökresultat med hjälp av SDK:ets search
metod.
name
och url
för det första resultatet visas.
Lägg till den här koden i Python-projektet:
# 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))
Kör programmet.
Rensa resurser
När du är klar med det här projektet bör du ta bort din prenumerationsnyckel från programmets kod och inaktivera den virtuella miljön.