البدء السريع: استخدام مكتبة عميل Bing لبحث الويب

تحذير

في 30 أكتوبر 2020، انتقلت واجهات برمجة تطبيقات البحث Bing من الخدمات المعرفية إلى خدمات البحث Bing. يتم توفير هذه الوثائق للرجوع إليها فقط. للحصول على الوثائق المحدثة، راجع وثائق واجهة برمجة تطبيقات البحث Bing. للحصول على إرشادات حول إنشاء موارد Azure جديدة للبحث Bing، راجع إنشاء مورد بحث Bing خلال Azure Marketplace.

تجعل مكتبة عميل The Bing Web Search من السهل دمج Bin Web Search في تطبيق #C الخاص بك. في هذا التشغيل السريع، ستتعرف على كيفية إنشاء مثيل لعميل وإرسال طلب وطباعة الاستجابة.

هل تريد رؤية الكود الآن؟ تتوفر نماذج لمكتبات عميل Bing Search عن .NET على GitHub.

المتطلبات الأساسية

إليك بعض الأشياء التي ستحتاج إليها قبل إجراء التشغيل السريع:

أنشئ مورد Azure.

ابدأ باستخدام Bing Web Search API من خلال إنشاء أحد الموارد التالية لـAzure.

مورد Bing Search v7.

  • متوفر من خلال بوابة Azure لطالما لم تحذف المورد.
  • استخدم مستوى التسعير المجاني لتجربة الخدمة وترقيتها لاحقاً إلي المستوى المدفوع الخاص بعملية الإنتاج.

موارد متعددة الخدمات

  • متوفر من خلال مدخل Azure إلى أن تقوم بحذف المورد.
  • استخدم نفس المفتاح ونقطة النهاية للتطبيقات الخاصة بك، عبر الخدمات المعرفية المتعددة.

إنشاء مشروع وتثبيت التبعيات

تلميح

احصل على أحدث كود كحل لـVisual Studio من GitHub.

الخطوة الأولى هي إنشاء مشروع جديد لوحدة التحكم. إذا كنت بحاجة إلى مساعدة في إعداد مشروع وحدة تحكم، انظر Hello World -- Your First Program (C# Programming Guide). لاستخدام sdkBing Web Search SDK في التطبيق الخاص بك، ستحتاج إلى تثبيت Microsoft.Azure.CognitiveServices.Search.WebSearch باستخدام NuGet Package Manager.

تقوم حزمةWeb Search SDK بتثبيت:

  • Microsoft.Rest.ClientRuntime
  • Microsoft.Rest.ClientRuntime.Azure
  • ⁧⁩Newtonsoft.Js⁩

إعلان التبعيات

افتح المشروع في Visual Studio أو Visual Studio Code واستورد هذه التبعيات:

using System;
using System.Collections.Generic;
using Microsoft.Azure.CognitiveServices.Search.WebSearch;
using Microsoft.Azure.CognitiveServices.Search.WebSearch.Models;
using System.Linq;
using System.Threading.Tasks;

إنشاء تقنية scaffolding للمشروع

عند إنشاء مشروع وحدة التحكم الجديدة الخاصة بك، يجب أن يكون قد تم إنشاء مساحة اسم وفئة للتطبيق الخاص بك. يجب أن يطابق برنامجك المثال التالي:

namespace WebSearchSDK
{
    class YOUR_PROGRAM
    {

        // The code in the following sections goes here.

    }
}

في الأقسام التالية، سنقوم ببناء نموذج التطبيق الخاص بنا ضمن هذه الفئة.

إنشاء طلب

يُنشئ هذا الكود استعلام البحث.

public static async Task WebResults(WebSearchClient client)
{
    try
    {
        var webData = await client.Web.SearchAsync(query: "Yosemite National Park");
        Console.WriteLine("Searching for \"Yosemite National Park\"");

        // Code for handling responses is provided in the next section...

    }
    catch (Exception ex)
    {
        Console.WriteLine("Encountered exception. " + ex.Message);
    }
}

معالجة الاستجابة

بعد ذلك، دعونا نضف هذا الكود لتحليل الاستجابة وطباعة النتائج. Nameتتم Url طباعة صفحة الويب الأولى والصورة والمقالة الإخبارية والفيديو إذا كانت موجودة في كائن الاستجابة.

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

إعلان الطريقة الرئيسية

في هذا التطبيق، تتضمن الطريقة الرئيسية التعليمات البرمجية التي تقوم بإنشاء مثيل للعميل، والتحقق من صحة subscriptionKeyوالمكالمات WebResults. تأكد من إدخال مفتاح اشتراك صالح لحساب Azure قبل المتابعة.

static async Task Main(string[] args)
{
    var client = new WebSearchClient(new ApiKeyServiceClientCredentials("YOUR_SUBSCRIPTION_KEY"));

    await WebResults(client);

    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
}

شغّل التطبيق

دعونا نُشغل التطبيق!

dotnet run

تحديد الوظائف ونتائج التصفية

والآن بعد إجراء أول بحث في Bing Web Search API، دعنا نلقِ نظرة على بعض الوظائف التي تسلط الضوء على وظائف SDK لتحسين الاستعلامات ونتائج التصفية. يمكن إضافة كل وظيفة إلى تطبيق C# الذي تم إنشاؤه في القسم السابق.

تحديد عدد النتائج التي يتم إرجاعها بواسطة Bing

يستخدم هذا النموذج count المعلمات offset للحد من عدد النتائج التي تم إرجاعها لـ "أفضل المطاعم في سياتل". NameتتمUrl طباعة النتائج الأولى.

  1. للبدء، أضف الكود إلى مشروعك:

    public static async Task WebResultsWithCountAndOffset(WebSearchClient client)
    {
        try
        {
            var webData = await client.Web.SearchAsync(query: "Best restaurants in Seattle", offset: 10, count: 20);
            Console.WriteLine("\r\nSearching for \" Best restaurants in Seattle \"");
    
            if (webData?.WebPages?.Value?.Count > 0)
            {
                var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();
    
                if (firstWebPagesResult != null)
                {
                    Console.WriteLine("Web Results #{0}", webData.WebPages.Value.Count);
                    Console.WriteLine("First web page name: {0} ", firstWebPagesResult.Name);
                    Console.WriteLine("First web page URL: {0} ", firstWebPagesResult.Url);
                }
                else
                {
                    Console.WriteLine("Couldn't find first web result!");
                }
            }
            else
            {
                Console.WriteLine("Didn't see any Web data..");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Encountered exception. " + ex.Message);
        }
    }
    
  2. أضف WebResultsWithCountAndOffsetإلى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. شغّل التطبيق.

تصفية الأخبار

يستخدم هذا النموذج response_filter المعلمة لتصفية نتائج البحث. تقتصر نتائج البحث التي تم إرجاعها على المقالات الإخبارية لـ "Microsoft". NameتتمUrl طباعة النتائج الأولى.

  1. للبدء، أضف الكود إلى مشروعك:

    public static async Task WebSearchWithResponseFilter(WebSearchClient client)
    {
        try
        {
            IList<string> responseFilterstrings = new List<string>() { "news" };
            var webData = await client.Web.SearchAsync(query: "Microsoft", responseFilter: responseFilterstrings);
            Console.WriteLine("\r\nSearching for \" Microsoft \" with response filter \"news\"");
    
            if (webData?.News?.Value?.Count > 0)
            {
                var firstNewsResult = webData.News.Value.FirstOrDefault();
    
                if (firstNewsResult != null)
                {
                    Console.WriteLine("News Results #{0}", webData.News.Value.Count);
                    Console.WriteLine("First news result name: {0} ", firstNewsResult.Name);
                    Console.WriteLine("First news result URL: {0} ", firstNewsResult.Url);
                }
                else
                {
                    Console.WriteLine("Couldn't find first News results!");
                }
            }
            else
            {
                Console.WriteLine("Didn't see any News data..");
            }
    
        }
        catch (Exception ex)
        {
            Console.WriteLine("Encountered exception. " + ex.Message);
        }
    }
    
  2. أضف WebResultsWithCountAndOffsetإلى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. شغّل التطبيق.

استخدام البحث الآمن وعدد الإجابات وتصفية الترقية

يستخدم هذا النموذج answer_countpromote المعلمات safe_search لتصفية نتائج البحث عن "مقاطع فيديو موسيقية". NameتتمContentUrl طباعة النتائج الأولى.

  1. للبدء، أضف الكود إلى مشروعك:

    public static async Task WebSearchWithAnswerCountPromoteAndSafeSearch(WebSearchClient client)
    {
        try
        {
            IList<string> promoteAnswertypeStrings = new List<string>() { "videos" };
            var webData = await client.Web.SearchAsync(query: "Music Videos", answerCount: 2, promote: promoteAnswertypeStrings, safeSearch: SafeSearch.Strict);
            Console.WriteLine("\r\nSearching for \"Music Videos\"");
    
            if (webData?.Videos?.Value?.Count > 0)
            {
                var firstVideosResult = webData.Videos.Value.FirstOrDefault();
    
                if (firstVideosResult != null)
                {
                    Console.WriteLine("Video Results # {0}", webData.Videos.Value.Count);
                    Console.WriteLine("First Video result name: {0} ", firstVideosResult.Name);
                    Console.WriteLine("First Video result URL: {0} ", firstVideosResult.ContentUrl);
                }
                else
                {
                    Console.WriteLine("Couldn't find videos results!");
                }
            }
            else
            {
                Console.WriteLine("Didn't see any data..");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Encountered exception. " + ex.Message);
        }
    }
    
  2. أضف WebResultsWithCountAndOffsetإلى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. شغّل التطبيق.

تنظيف الموارد

عند الانتهاء من هذا المشروع، تأكد من إزالة مفتاح الاشتراك من كود البرنامج.

الخطوات التالية

تسهل مكتبة عميل Bing Web Search من دمج بحث الويب Bing في تطبيق Java الخاص بك. في هذه البداية السريعة، ستتعلم كيفية إرسال طلب، وتلقي استجابة JSON، وتصفية النتائج وتحليلها.

تريد أن ترى الرمز الآن؟ عينات مكتبات عميل بحث Bing لـ Java متوفرة على GitHub.

المتطلبات الأساسية

إليك بعض الأشياء التي ستحتاجها قبل تشغيل هذه البداية السريعة:

أنشئ مورد Azure.

ابدأ باستخدام Bing Web Search API من خلال إنشاء أحد الموارد التالية لـAzure.

مورد Bing Search v7.

  • متوفر من خلال بوابة Azure لطالما لم تحذف المورد.
  • استخدم مستوى التسعير المجاني لتجربة الخدمة وترقيتها لاحقاً إلي المستوى المدفوع الخاص بعملية الإنتاج.

موارد متعددة الخدمات

  • متوفر من خلال مدخل Azure إلى أن تقوم بحذف المورد.
  • استخدم نفس المفتاح ونقطة النهاية للتطبيقات الخاصة بك، عبر الخدمات المعرفية المتعددة.

قم بإنشاء مشروع وقم بإعداد ملف POM الخاص بك

قم بإنشاء مشروع Java جديد باستخدام Maven أو أداة أتمتة البناء المفضلة لديك. بافتراض أنك تستخدم Maven، أضف الأسطر التالية إلى ملف نموذج كائن المشروع (POM). استبدل جميع مثيلات mainClass مع التطبيق الخاص بك.

<build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.4.0</version>
        <configuration>
          <!--Your comment
            Replace the mainClass with the path to your Java application.
            It should begin with com and doesn't require the .java extension.
            For example: com.bingwebsearch.app.BingWebSearchSample. This maps to
            The following directory structure:
            src/main/java/com/bingwebsearch/app/BingWebSearchSample.java.
          -->
          <mainClass>com.path.to.your.app.APP_NAME</mainClass>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>attached</goal>
            </goals>
            <configuration>
              <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
              </descriptorRefs>
              <archive>
                <manifest>
                  <!--Your comment
                    Replace the mainClass with the path to your Java application.
                    For example: com.bingwebsearch.app.BingWebSearchSample.java.
                    This maps to the following directory structure:
                    src/main/java/com/bingwebsearch/app/BingWebSearchSample.java.
                  -->
                  <mainClass>com.path.to.your.app.APP_NAME.java</mainClass>
                </manifest>
              </archive>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure</artifactId>
      <version>1.9.0</version>
    </dependency>
    <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>3.3</version>
    </dependency>
    <dependency>
      <groupId>com.microsoft.azure.cognitiveservices</groupId>
      <artifactId>azure-cognitiveservices-websearch</artifactId>
      <version>1.0.1</version>
    </dependency>
  </dependencies>

أعلن التبعيات

افتح مشروعك في IDE أو المحرر المفضل لديك واستورد هذه التبعيات:

import com.microsoft.azure.cognitiveservices.search.websearch.BingWebSearchAPI;
import com.microsoft.azure.cognitiveservices.search.websearch.BingWebSearchManager;
import com.microsoft.azure.cognitiveservices.search.websearch.models.ImageObject;
import com.microsoft.azure.cognitiveservices.search.websearch.models.NewsArticle;
import com.microsoft.azure.cognitiveservices.search.websearch.models.SearchResponse;
import com.microsoft.azure.cognitiveservices.search.websearch.models.VideoObject;
import com.microsoft.azure.cognitiveservices.search.websearch.models.WebPage;

إذا قمت بإنشاء المشروع باستخدام Maven، فيجب أن يتم الإعلان عن الحزمة بالفعل. خلاف ذلك، أعلن عن الحزمة الآن. على سبيل المثال:

package com.bingwebsearch.app

قم بتعريف فئة BingWebSearchSample

أعلن BingWebSearchSample الصف الدراسي. سيتضمن معظم التعليمة البرمجية الخاص بنا بما في ذلك طريقة main.

public class BingWebSearchSample {

// The code in the following sections goes here.

}

بناء طلب

ال runSample الطريقة التي تعيش في BingWebSearchSample الطبقة، يبني الطلب. انسخ هذا الرمز في التطبيق الخاص بك:

public static boolean runSample(BingWebSearchAPI client) {
    /*
     * This function performs the search.
     *
     * @param client instance of the Bing Web Search API client
     * @return true if sample runs successfully
     */
    try {
        /*
         * Performs a search based on the .withQuery and prints the name and
         * url for the first web pages, image, news, and video result
         * included in the response.
         */
        System.out.println("Searched Web for \"Xbox\"");
        // Construct the request.
        SearchResponse webData = client.bingWebs().search()
            .withQuery("Xbox")
            .withMarket("en-us")
            .withCount(10)
            .execute();

// Code continues in the next section...

تعامل مع الاستجابة

بعد ذلك، دعنا نضيف بعض التعليمات البرمجية لتحليل الاستجابة وطباعة النتائج. name و url بالنسبة إلى صفحة الويب الأولى، تتم طباعة الصورة والمقال الإخباري والفيديو عند تضمينها في كائن الاستجابة.

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

أعلن عن الطريقة الرئيسية

في هذا التطبيق، تتضمن الطريقة الرئيسية التعليمات البرمجية التي تقوم بإنشاء مثيل للعميل، والتحقق من صحة subscriptionKeyوالمكالمات runSample. تأكد من إدخال مفتاح اشتراك صالح لحساب Azure الخاص بك قبل المتابعة.

public static void main(String[] args) {
    try {
        // Enter a valid subscription key for your account.
        final String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
        // Instantiate the client.
        BingWebSearchAPI client = BingWebSearchManager.authenticate(subscriptionKey);
        // Make a call to the Bing Web Search API.
        runSample(client);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

قم بتشغيل البرنامج.

الخطوة الأخيرة هي تشغيل برنامجك!

mvn compile exec:java

تنظيف الموارد

عند الانتهاء من هذا المشروع، تأكد من إزالة مفتاح الاشتراك الخاص بك من رمز البرنامج.

الخطوات التالية

راجع أيضًا

تجعل مكتبة العميل الخاصة بـ Bing Web Search من السهل دمج Bing Web Search إلى Node.js application الخاص بك. في هذا التشغيل السريع، ستتعرف على كيفية إنشاء مثيل لعميل وإرسال طلب وطباعة الاستجابة.

هل تريد رؤية الرمز الآن؟ تتوفر نماذج لمكتبات العملاء الخاصة بـBing Search عن JavaScriptعلى GitHub.

المتطلبات الأساسية

إليك بعض الأشياء التي ستحتاج إليها قبل إجراء التشغيل السريع:

  • Node.js 6 أو الأحدث.
  • مفتاح الاشتراك

أنشئ مورد Azure.

ابدأ باستخدام Bing Web Search API من خلال إنشاء أحد الموارد التالية لـAzure.

مورد Bing Search v7.

  • متوفر من خلال بوابة Azure لطالما لم تحذف المورد.
  • استخدم مستوى التسعير المجاني لتجربة الخدمة وترقيتها لاحقاً إلي المستوى المدفوع الخاص بعملية الإنتاج.

موارد متعددة الخدمات

  • متوفر من خلال مدخل Azure إلى أن تقوم بحذف المورد.
  • استخدم نفس المفتاح ونقطة النهاية للتطبيقات الخاصة بك، عبر الخدمات المعرفية المتعددة.

إعداد بيئة التطوير

لنبدأ بتهيئة بيئة تطوير للمشاريع الخاصة بنا وهو مشروع Node.js.

  1. أنشئ دليلاً جديداً للمشروع الخاص بك:

    mkdir YOUR_PROJECT
    
  2. أنشئ ملف الحزمة الجديد:

    cd YOUR_PROJECT
    npm init
    
  3. الآن، لتثبيت بعض Azure modules وإضافتها إلىpackage.json:

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

أنشئ مشروعاً وأعلن عن modules المطلوبة

في نفس الدليل الخاص بك package.json، أنشئ مشروع Node.js جديداً باستخدام IDE أو editor المفضلين لديك. على سبيل المثال: sample.js.

بعد ذلك، انسخ هذا الرمز إلى المشروع الخاص بك. تحميل modules المثبتة في القسم السابق.

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

أنشئ مثيلاً للعميل

يعمل هذا الرمز على إنشاء مثيل للعميل واستخدام@azure/cognitiveservices-websearch module. تأكد من إدخال مفتاح الاشتراك الساري لحساب Azure قبل المتابعة.

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

تقديم طلب وطباعة النتائج

استخدم العميل لإرسال استعلام البحث إلى Bing Web Search. إذا كانت الاستجابة تشمل النتائج لأي من العناصر فيproperties الصفيف، result.value تتم طباعة وحدة التحكم.

webSearchApiClient.web.search('seahawks').then((result) => {
    let properties = ["images", "webPages", "news", "videos"];
    for (let i = 0; i < properties.length; i++) {
        if (result[properties[i]]) {
            console.log(result[properties[i]].value);
        } else {
            console.log(`No ${properties[i]} data`);
        }
    }
}).catch((err) => {
    throw err;
})

قم بتشغيل البرنامج.

الخطوة الأخيرة هي تشغيل برنامجك!

تنظيف الموارد

عند الانتهاء من هذا المشروع، تأكد من إزالة مفتاح الاشتراك الخاص بك من رمز البرنامج.

الخطوات التالية

راجع أيضًا

تسهل مكتبة عميل Bing Web Search عملية تكامل Bing Web Search مع تطبيق Python لديك. في دليل التشغيل السريع هذا، ستتعرف على كيفية إرسال طلب، وتلقي استجابة JSON، وتصفية النتائج وتحليلها.

هل تريد رؤية التعليمات البرمجية الآن؟ تتوفر عينات من مكتبات عميل Bing Search للغة Python على GitHub.

المتطلبات الأساسية

تتوافق مجموعة SDK لدى Bing Web Search مع لغة Python بالإصدار 2.7 أو 3.6 أو الإصدارات الأحدث. نوصي باستخدام بيئة ظاهرية مع دليل التشغيل السريع هذا.

  • Python بالإصدار 2.7 أو 3.6 أو أحدث
  • virtualenv لـ Python بالإصدار 2.7
  • venv لـ Python بالإصدار 3.x

أنشئ مورد Azure.

ابدأ باستخدام Bing Web Search API من خلال إنشاء أحد الموارد التالية لـAzure.

مورد Bing Search v7.

  • متوفر من خلال بوابة Azure لطالما لم تحذف المورد.
  • استخدم مستوى التسعير المجاني لتجربة الخدمة وترقيتها لاحقاً إلي المستوى المدفوع الخاص بعملية الإنتاج.

موارد متعددة الخدمات

  • متوفر من خلال مدخل Azure إلى أن تقوم بحذف المورد.
  • استخدم نفس المفتاح ونقطة النهاية للتطبيقات الخاصة بك، عبر الخدمات المعرفية المتعددة.

إنشاء البيئة الظاهرية وتكوينها

تختلف تعليمات إعداد وتكوين البيئة ظاهرية في Python بالإصدار 2.x وPython بالإصدار 3.x. اتبع الخطوات أدناه لإنشاء وتهيئة بيئتك الظاهرية.

Python بالإصدار 2.x

إنشاء بيئة ظاهرية باستخدام virtualenv لدى Python بالإصدار 2.7:

virtualenv mytestenv

تنشيط البيئة لديك:

cd mytestenv
source bin/activate

تثبيت تبعيات SDK لدى Bing Web Search:

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

Python 3.x

إنشاء بيئة ظاهرية باستخدام venv لدى Python بالإصدار 3.x:

python -m venv mytestenv

تنشيط البيئة لديك:

mytestenv\Scripts\activate.bat

تثبيت تبعيات SDK لدى Bing Web Search:

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

إنشاء عميل وطباعة النتائج الأولى

الآن بعد أن أعددت بيئتك الظاهرية وقمت بتثبيت التبعيات، فلنحاول إنشاء عميل. سيقوم العميل بمعالجة الطلبات والاستجابات من جانب واجهة برمجة التطبيقات في Bing Web Search.

إذا كانت الاستجابة تتضمن صفحات ويب أو صورًا أو أخبارًا أو مقاطع فيديو، فستتم طباعة النتيجة الأولى لكل منها.

  1. أنشئ مشروع Python جديدًا باستخدام IDE أو المحرر المفضل لديك.

  2. انسخ عينة التعليمات البرمجية في المشروع لديك. يمكن أن يمثل endpoint نقطة النهاية العامة أدناه، أو المجال الفرعي لدى نقطة النهاية التي يتم عرضها في مدخل Azure لموردك.:

    # Import required modules.
    from azure.cognitiveservices.search.websearch import WebSearchClient
    from azure.cognitiveservices.search.websearch.models import SafeSearch
    from msrest.authentication import CognitiveServicesCredentials
    
    # Replace with your subscription key.
    subscription_key = "YOUR_SUBSCRIPTION_KEY"
    
    # Instantiate the client and replace with your endpoint.
    client = WebSearchClient(endpoint="YOUR_ENDPOINT", credentials=CognitiveServicesCredentials(subscription_key))
    
    # Make a request. Replace Yosemite if you'd like.
    web_data = client.web.search(query="Yosemite")
    print("\r\nSearched for Query# \" Yosemite \"")
    
    '''
    Web pages
    If the search response contains web pages, the first result's name and url
    are printed.
    '''
    if hasattr(web_data.web_pages, 'value'):
    
        print("\r\nWebpage Results#{}".format(len(web_data.web_pages.value)))
    
        first_web_page = web_data.web_pages.value[0]
        print("First web page name: {} ".format(first_web_page.name))
        print("First web page URL: {} ".format(first_web_page.url))
    
    else:
        print("Didn't find any web pages...")
    
    '''
    Images
    If the search response contains images, the first result's name and url
    are printed.
    '''
    if hasattr(web_data.images, 'value'):
    
        print("\r\nImage Results#{}".format(len(web_data.images.value)))
    
        first_image = web_data.images.value[0]
        print("First Image name: {} ".format(first_image.name))
        print("First Image URL: {} ".format(first_image.url))
    
    else:
        print("Didn't find any images...")
    
    '''
    News
    If the search response contains news, the first result's name and url
    are printed.
    '''
    if hasattr(web_data.news, 'value'):
    
        print("\r\nNews Results#{}".format(len(web_data.news.value)))
    
        first_news = web_data.news.value[0]
        print("First News name: {} ".format(first_news.name))
        print("First News URL: {} ".format(first_news.url))
    
    else:
        print("Didn't find any news...")
    
    '''
    If the search response contains videos, the first result's name and url
    are printed.
    '''
    if hasattr(web_data.videos, 'value'):
    
        print("\r\nVideos Results#{}".format(len(web_data.videos.value)))
    
        first_video = web_data.videos.value[0]
        print("First Videos name: {} ".format(first_video.name))
        print("First Videos URL: {} ".format(first_video.url))
    
    else:
        print("Didn't find any videos...")
    
  3. استبدال SUBSCRIPTION_KEY بمفتاح اشتراك صالح.

  4. استبدل YOUR_ENDPOINT بعنوان URL لنقطة النهاية في المدخل وأزل قسم "bing/v7.0" من نقطة النهاية.

  5. قم بتشغيل البرنامج. على سبيل المثال: python your_program.py.

تحديد الوظائف وتصفية النتائج

الآن بعد أن أجريت الاستدعاء الأول لواجهة برمجة التطبيقات في Bing Web Search، دعنا ننظر إلى بعض الوظائف. تسلط الأقسام التالية الضوء على وظائف SDK لتحسين الاستعلامات وتصفية النتائج. يمكن إضافة كل وظيفة إلى برنامج Python الذي أنشأته في القسم السابق.

تقييد عدد النتائج التي يتم إرجاعها بواسطة Bing

تستخدم هذه العينة المعلمتين count وoffset لتقييد عدد النتائج التي يتم إرجاعها باستخدام الأسلوب search لمجموعة SDK. تتم طباعة النتائج الأولى لـ name وurl.

  1. أضف هذه التعليمات البرمجية إلى مشروع Python لديك:

     # Declare the function.
     def web_results_with_count_and_offset(subscription_key):
         client = WebSearchAPI(CognitiveServicesCredentials(subscription_key))
    
         try:
             '''
             Set the query, offset, and count using the SDK's search method. See:
             https://docs.microsoft.com/python/api/azure-cognitiveservices-search-websearch/azure.cognitiveservices.search.websearch.operations.weboperations?view=azure-python.
             '''
             web_data = client.web.search(query="Best restaurants in Seattle", offset=10, count=20)
             print("\r\nSearching for \"Best restaurants in Seattle\"")
    
             if web_data.web_pages.value:
                 '''
                 If web pages are available, print the # of responses, and the first and second
                 web pages returned.
                 '''
                 print("Webpage Results#{}".format(len(web_data.web_pages.value)))
    
                 first_web_page = web_data.web_pages.value[0]
                 print("First web page name: {} ".format(first_web_page.name))
                 print("First web page URL: {} ".format(first_web_page.url))
    
             else:
                 print("Didn't find any web pages...")
    
         except Exception as err:
             print("Encountered exception. {}".format(err))
    
  2. قم بتشغيل البرنامج.

تصفية الأخبار وتحديثها

تستخدم هذه العينة المعلمتين response_filter وfreshness لتصفية نتائج البحث باستخدام الأسلوب search لمجموعة SDK. تقتصر نتائج البحث التي تم إرجاعها على المقالات الإخبارية والصفحات التي اكتشفها Bing خلال الـ 24 ساعة الماضية. تتم طباعة النتائج الأولى لـ name وurl.

  1. أضف هذه التعليمات البرمجية إلى مشروع Python لديك:

    # Declare the function.
    def web_search_with_response_filter(subscription_key):
        client = WebSearchAPI(CognitiveServicesCredentials(subscription_key))
        try:
            '''
            Set the query, response_filter, and freshness using the SDK's search method. See:
            https://docs.microsoft.com/python/api/azure-cognitiveservices-search-websearch/azure.cognitiveservices.search.websearch.operations.weboperations?view=azure-python.
            '''
            web_data = client.web.search(query="xbox",
                response_filter=["News"],
                freshness="Day")
            print("\r\nSearching for \"xbox\" with the response filter set to \"News\" and freshness filter set to \"Day\".")
    
            '''
            If news articles are available, print the # of responses, and the first and second
            articles returned.
            '''
            if web_data.news.value:
    
                print("# of news results: {}".format(len(web_data.news.value)))
    
                first_web_page = web_data.news.value[0]
                print("First article name: {} ".format(first_web_page.name))
                print("First article URL: {} ".format(first_web_page.url))
    
                print("")
    
                second_web_page = web_data.news.value[1]
                print("\nSecond article name: {} ".format(second_web_page.name))
                print("Second article URL: {} ".format(second_web_page.url))
    
            else:
                print("Didn't find any news articles...")
    
        except Exception as err:
            print("Encountered exception. {}".format(err))
    
    # Call the function.
    web_search_with_response_filter(subscription_key)
    
  2. قم بتشغيل البرنامج.

استخدام البحث الآمن وعدد الإجابات وعامل تصفية الترقية

تستخدم هذه العينة المعلمات answer_count وpromote وsafe_search لتصفية نتائج البحث باستخدام الأسلوب search لمجموعة SDK. يتم عرض النتائج الأولى لـ name وurl.

  1. أضف هذه التعليمات البرمجية إلى مشروع Python لديك:

    # Declare the function.
    def web_search_with_answer_count_promote_and_safe_search(subscription_key):
    
        client = WebSearchAPI(CognitiveServicesCredentials(subscription_key))
    
        try:
            '''
            Set the query, answer_count, promote, and safe_search parameters using the SDK's search method. See:
            https://docs.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. قم بتشغيل البرنامج.

تنظيف الموارد

عند الانتهاء من هذا المشروع، تأكد من إزالة مفتاح الاشتراك من التعليمات البرمجية للبرنامج وإلغاء تنشيط البيئة الظاهرية.

الخطوات التالية

راجع أيضًا