65.9K
CodeProject 正在变化。 阅读更多。
Home

开始使用 Bing 搜索 API

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.80/5 (6投票s)

2017年12月19日

MIT

4分钟阅读

viewsIcon

20914

downloadIcon

355

使用 Bing 搜索 API 端点搜索 Web 的基本代码场景

引言

Bing 搜索 API 是一组 REST 接口,可根据任何能够生成 Web 请求的编程语言的查询来查找网页、新闻、图片、视频、实体、相关搜索、拼写更正等。需要从 Web 获取信息的应用程序使用 Bing 搜索 API 以 JSON 格式获取满足其要求的结果。

Bing 搜索 API 包含以下类型的专用终结点

  • Bing Web 搜索 API - 包括网页以及下面提到的所有其他类型,例如图片、视频、新闻、相关搜索、拼写更正等。
  • Bing 新闻搜索 API - 提供与用户查询相关的新闻项。它还提供特定类别(如健康、体育等)的新闻,以及任何时间点的新闻热点。
  • Bing 视频搜索 API - 返回相关视频。它还提供类似视频和热门视频的终结点。
  • Bing 图片搜索 API - 与视频搜索 API 类似,此 API 具有 3 个终结点:图片搜索、相似图片和热门图片。
  • Bing 实体搜索 API - 关于人员、地点、组织、产品和其他概念的摘要信息
  • Bing 自定义搜索 API - 支持自定义搜索,以从 Web 上的特定来源(域、子网站或网页)获取结果。
  • Bing 自动建议 API - 为部分字符串提供查询完成功能。
  • Bing 拼写检查 API - 为短字符串或大段落提供拼写和语法更正

要试用 Bing 搜索 API,您需要一个 API 访问密钥,可在 Azure: 试用认知服务 获取。

基本程序化搜索

为简单起见,以下代码示例使用了 Bing Web 搜索 API。其他终结点使用类似的过程。Bing Web 搜索 API 可用于为给定查询查找网站、图片、视频、新闻和实体等 Web 资源。您可以使用任何能够向以下终结点发送 GET 请求的语言编写代码

https://api.cognitive.microsoft.com/bing/v7.0/search?q=<searchString>

每次请求 Bing Web 搜索 API 都必须包含一个标头,其中包含 Ocp-Apim-Subscription-Key,这是您的私有访问密钥。访问密钥可用于探索这些 API。

使用访问密钥,Java 中的基本代码场景可能如下所示

    // Replace the accessKey string value with your valid access key.
    static String accessKey = "Enter key here";

    static String host = "https://api.cognitive.microsoft.com";
    static String path = "/bing/v7.0/search";

    // Replace the following searchQuery with your query string.
    static String searchQuery= "Code Project Top Articles";

    // construct URL of search request (endpoint + query string)
    URL url = new URL(host + path + "?q=" +  URLEncoder.encode(searchQuery, "UTF-8"));
    HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();

    // Set the access key header.
    connection.setRequestProperty("Ocp-Apim-Subscription-Key", accessKey);

    // Receive JSON body
    InputStream stream = connection.getInputStream();
    String response = new Scanner(stream).useDelimiter("\\A").next();

    // Construct result object for return.  
    SearchResults results = new SearchResults(new HashMap<String, String>(), response);
    stream.close();

有关此摘录的详细信息,请参阅 Java 项目源代码

结果的解析将在本文的最后一节进行讨论。

以下代码片段显示了 C# 中的请求代码序列。

  // Replace the accessKey string value with your valid access key.
  const string accessKey = "Enter key here";

  //  The endpoint URI. 
  const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/search"; 

  // Replace the searchQuery below to search for your query
  const string searchQuery = "Code Project Top Articles";

  // Construct the URI of the search request
  var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);

  // Create the Web request.
  WebRequest request = HttpWebRequest.Create(uriQuery);

  // Set the access key header.       
  request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
  // Send the request.
  HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
  
  // Read the response.
  string json = new StreamReader(response.GetResponseStream()).ReadToEnd();

有关此摘录的详细信息,请参阅 C# 项目源代码

结果的解析将在本文的最后一节进行讨论。

其他 Bing API 的终结点

本节总结了各种 Bing 搜索 API 的终结点。

Bing Web 搜索 API

如上一个示例中所述,Web 搜索终结点除了拼写更正外,还返回网页、新闻、图片、视频、实体和相关搜索。Web 搜索 API 终结点如下

GET https://api.cognitive.microsoft.com/bing/v7.0/search?q=”Code+Project+Top+Articles”

Bing 新闻搜索 API

Bing 新闻搜索 API 支持三个终结点。

以下终结点返回给定查询的新闻文章

GET https://api.cognitive.microsoft.com/bing/v7.0/news/search?q=”Artificial+Intelligence”

接下来的第二个终结点返回特定类别(如健康、商业、体育等)的新闻文章。

GET https://api.cognitive.microsoft.com/bing/v7.0/news?category=”health”

最后,第三个终结点返回当前在社交网络上流行的新闻主题

GET https://api.cognitive.microsoft.com/bing/v7.0/news/trendingtopics

Bing 视频搜索 API

Bing 视频搜索 API 具有三个终结点。以下终结点返回给定查询的视频

GET https://api.cognitive.microsoft.com/bing/v7.0/videos/search?q=”sushi+recipe”

接下来的第二个视频终结点可用于获取与由 Your_Video_Id 标识的视频相似的视频。“Modules”参数用于获取与“id”参数中提到的视频相关的视频。

GET https://api.cognitive.microsoft.com/bing/v7.0/videos/details?modules=”RelatedVideos”&id=”Your_Video_Id”

最后一个视频终结点返回当前热门的视频。结果按不同类别进行分隔,例如,基于值得关注的人物或事件。

GET https://api.cognitive.microsoft.com/bing/v7.0/videos/trending

Bing 图片搜索 API

Bing 图片搜索 API 具有三个终结点,其功能与 Bing 视频搜索终结点类似。以下终结点返回与给定查询相关的图片。

GET https://api.cognitive.microsoft.com/bing/v7.0/images/search?q=”Quantum+Computer”

第二个终结点提供关于给定图片的见解,例如相似图片或给定图片的来源。“Modules”参数可用于派生各种见解。以下请求搜索与给定图像 URL 的图像相似的图像。

GET https://api.cognitive.microsoft.com/bing/v7.0/images/details?Modules=”SimilarImages”&imgURL=”YOUR_URL”

最后一个图片终结点返回热门图片。

GET https://api.cognitive.microsoft.com/bing/v7.0/images/trending

Bing 自定义搜索

Bing 自定义搜索根据用户指定的来源返回结果。有关定义来源的信息,请参阅 Bing 自定义搜索。与其他终结点一样,查询由 URL 参数定义:?q=” ”

GET https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search?q="Redmond Real Estate"

Bing 自动建议

Bing 自动建议接受部分查询,并根据用户的过去查询或热门查询返回其他查询的建议。结果可用于自动完成短语或术语。

GET https://api.cognitive.microsoft.com/bing/v7.0/Suggestions?q=”cognitive ”

Bing 拼写检查

Bing 拼写检查接受文本并检查拼写和语法。以下终结点返回的响应包括原始文本和用于更正它的标记建议。

GET https://api.cognitive.microsoft.com/bing/v7.0/SpellCheck?text=”Th is contains erroneous spll ing and grammer”

JSON 搜索结果

Bing 搜索 API 以 JSON 对象的形式返回结果,以便作为文本进行解析。您可以使用以下代码将 JSON 响应解析为控制台显示

Java JSON 解析示例

    // pretty-printer for JSON; uses GSON parser to parse and re-serialize results.
    public static String prettify(String json_text) {
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(json_text).getAsJsonObject();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        return gson.toJson(json);
    }

C# JSON 解析示例

        /// Formats the given JSON string by adding line breaks and indents.
        /// </summary>
        /// <param name="json">The raw JSON string to format.</param>
        /// <returns>The formatted JSON string.</returns>
        static string JsonPrettyPrint(string json)
        {
            if (string.IsNullOrEmpty(json))
                return string.Empty;

            json = json.Replace(Environment.NewLine, "").Replace("\t", "");

            StringBuilder sb = new StringBuilder();
            bool quote = false;
            bool ignore = false;
            char last = ' ';
            int offset = 0;
            int indentLength = 2;

            foreach (char ch in json)
            {
                switch (ch)
                {
                    case '"':
                        if (!ignore) quote = !quote;
                        break;
                    case '\\':
                        if (quote && last != '\\') ignore = true;
                        break;
                }

                if (quote)
                {
                    sb.Append(ch);
                    if (last == '\\' && ignore) ignore = false;
                }
                else
                {
                    switch (ch)
                    {
                        case '{':
                        case '[':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', ++offset * indentLength));
                            break;
                        case '}':
                        case ']':
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', --offset * indentLength));
                            sb.Append(ch);
                            break;
                        case ',':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', offset * indentLength));
                            break;
                        case ':':
                            sb.Append(ch);
                            sb.Append(' ');
                            break;
                        default:
                            if (quote || ch != ' ') sb.Append(ch);
                            break;
                    }
                }
                last = ch;
            }

            return sb.ToString().Trim();
        }

有关更多示例,请参阅以下 GitHub 仓库:cognitive-services-REST-api-samples

历史

  • 2017 年 12 月 20 日:初稿
  • 添加了访问密钥页面的链接
© . All rights reserved.