快速入門:使用 Python 來呼叫 Bing Web 搜尋 APIQuickstart: Use Python to call the Bing Web Search API

警告

Bing 搜尋 API 將從認知服務移至 Bing 搜尋服務。Bing Search APIs are moving from Cognitive Services to Bing Search Services. 2020 年 10 月 30 日 開始,所有 Bing 搜尋的新執行個體都必須依照 這裡所述的程序進行佈建。Starting October 30, 2020, any new instances of Bing Search need to be provisioned following the process documented here. 使用認知服務佈建的 Bing 搜尋 API 將在未來三年受到支援,或支援到您的 Enterprise 合約結束為止 (視何者先發生)。Bing Search APIs provisioned using Cognitive Services will be supported for the next three years or until the end of your Enterprise Agreement, whichever happens first. 如需移轉指示,請參閱 Bing 搜尋服務For migration instructions, see Bing Search Services.

使用本快速入門,第一次呼叫 Bing Web 搜尋 API。Use this quickstart to make your first call to the Bing Web Search API. 這個 Python 應用程式會將搜尋要求傳送給 API,並顯示 JSON 回應。This Python application sends a search request to the API, and shows the JSON response. 雖然此應用程式是以 Python 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。Although this application is written in Python, the API is a RESTful Web service compatible with most programming languages.

此範例在 MyBinder (英文) 上以 Jupyter Notebook 形式執行。This example is run as a Jupyter notebook on MyBinder. 若要加以執行,請選取啟動文件夾徽章:To run it, select the launch binder badge:

BinderBinder

必要條件Prerequisites

建立 Azure 資源Create an Azure resource

藉由建立下列其中一項 Azure 資源,開始使用 Bing Web 搜尋 API:Start using the Bing Web Search API by creating one of the following Azure resources:

Bing 搜尋 v7 資源Bing Search v7 resource

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。Available through the Azure portal until you delete the resource.
  • 使用免費定價層來試用服務,之後可升級至付費層以用於實際執行環境。Use the free pricing tier to try the service, and upgrade later to a paid tier for production.

多服務資源Multi-service resource

  • 您可以透過 Azure 入口網站取得該資源,直到將其刪除為止。Available through the Azure portal until you delete the resource.
  • 針對您的應用程式,跨多個認知服務使用相同的金鑰和端點。Use the same key and endpoint for your applications, across multiple Cognitive Services.

定義變數Define variables

  1. subscription_key 值換成您的 Azure 帳戶中有效的訂用帳戶金鑰。Replace the subscription_key value with a valid subscription key from your Azure account.

    subscription_key = "YOUR_ACCESS_KEY"
    assert subscription_key
    
  2. 宣告 Bing Web 搜尋 API 端點。Declare the Bing Web Search API endpoint. 您可以使用下列程式碼中的全域端點,或使用 Azure 入口網站中針對您的資源所顯示的自訂子網域端點。You can use the global endpoint in the following code, or use the custom subdomain endpoint displayed in the Azure portal for your resource.

    search_url = "https://api.cognitive.microsoft.com/bing/v7.0/search"
    
  3. (選擇性) 取代 search_term 的值以自訂搜尋查詢。Optionally, customize the search query by replacing the value for search_term.

    search_term = "Azure Cognitive Services"
    

發出要求Make a request

下列程式碼會使用 requests 程式庫呼叫 Bing Web 搜尋 API,並以 JSON 物件的形式傳回結果。This code uses the requests library to call the Bing Web Search API and return the results as a JSON object. API 金鑰會透過 headers 字典傳入,而搜尋字詞和查詢參數則會透過 params 字典傳入。The API key is passed in the headers dictionary, and the search term and query parameters are passed in the params dictionary.

如需完整的選項和參數清單,請參閱 Bing Web 搜尋 API v7For a complete list of options and parameters, see Bing Web Search API v7.

import requests

headers = {"Ocp-Apim-Subscription-Key": subscription_key}
params = {"q": search_term, "textDecorations": True, "textFormat": "HTML"}
response = requests.get(search_url, headers=headers, params=params)
response.raise_for_status()
search_results = response.json()

格式化並顯示回應Format and display the response

search_results 物件包含搜尋結果,以及相關查詢和網頁等中繼資料。The search_results object includes the search results, and such metadata as related queries and pages. 此程式碼會使用 IPython.display 程式庫來格式化回應,並顯示在瀏覽器中。This code uses the IPython.display library to format and display the response in your browser.

from IPython.display import HTML

rows = "\n".join(["""<tr>
                       <td><a href=\"{0}\">{1}</a></td>
                       <td>{2}</td>
                     </tr>""".format(v["url"], v["name"], v["snippet"])
                  for v in search_results["webPages"]["value"]])
HTML("<table>{0}</table>".format(rows))

GitHub 上的範例程式碼Sample code on GitHub

若在本機執行此程式碼,請參閱 GitHub 上提供的完整範例To run this code locally, see the complete sample available on GitHub.

後續步驟Next steps

另請參閱See also