快速入門:使用適用於 Python 的 Bing 影像搜尋 SDK 來搜尋影像Quickstart: Search for images with the Bing Image Search SDK for Python

Bing 影像搜尋 SDK 是 API 的包裝函式,而且功能相同,您可以透過此快速入門,完成初次使用此 SDK 進行的影像搜尋。Use this quickstart to make your first image search using the Bing Image Search SDK, which is a wrapper for the API and contains the same features. 這個簡單的 Python 應用程式會傳送影像搜尋查詢、剖析 JSON 回應,以及顯示第一個傳回影像的 URL。This simple Python application sends an image search query, parses the JSON response, and displays the URL of the first image returned.

此範例的原始程式碼可從 GitHub 取得,其中含有其他錯誤處理和註釋。The source code for this sample is available on GitHub with additional error handling and annotations.

必要條件Prerequisites

在「搜尋」 下取得認知服務存取金鑰Get a Cognitive Services access key under Search. 另請參閱認知服務定價 - Bing 搜尋 APISee also Cognitive Services Pricing - Bing Search API.

您必須有具備 Bing 搜尋 API 存取權的認知服務 API 帳戶You must have a Cognitive Services API account with access to the Bing Search APIs. 如果您沒有 Azure 訂用帳戶,可以建立免費帳戶If you don't have an Azure subscription, you can create an account for free. 繼續之前,您需要有啟動免費試用版後所提供的存取金鑰,或是從 Azure 儀表板中取得的付費訂用帳戶金鑰。Before continuing, You will need the access key provided after activating your free trial, or a paid subscription key from your Azure dashboard.

建立並初始化應用程式Create and initialize the application

  1. 在您慣用的 IDE 或編輯器中建立新的 Python 專案以及下列匯入:Create a new Python script in your favorite IDE or editor, and the following imports:

    from azure.cognitiveservices.search.imagesearch import ImageSearchAPI
    from msrest.authentication import CognitiveServicesCredentials
    
  2. 針對您的訂用帳戶金鑰和搜尋字詞建立變數。Create variables for your subscription key and search term.

    subscription_key = "Enter your key here"
    search_term = "canadian rockies"
    

建立影像搜尋用戶端Create the image search client

  1. 建立 CognitiveServicesCredentials 的執行個體,並使用它來將用戶端具現化:Create an instance of CognitiveServicesCredentials, and use it to instantiate the client:

    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
    
  2. 將搜尋查詢傳送到 Bing 影像搜尋 API:Send a search query to the Bing Image Search API:

    image_results = client.images.search(query=search_term)
    

    處理並檢視結果Process and view the results

剖析回應中所傳回的影像結果。Parse the image results returned in the response.

如果回應包含搜尋結果,請儲存第一個結果並列印出其詳細資料,例如縮圖 URL、原始 URL 及傳回影像的總數。If the response contains search results, store the first result and print out its details, such as a thumbnail URL, the original URL,along with the total number of returned images.

if image_results.value:
    first_image_result = image_results.value[0]
    print("Total number of images returned: {}".format(len(image_results.value)))
    print("First image thumbnail url: {}".format(
        first_image_result.thumbnail_url))
    print("First image content url: {}".format(first_image_result.content_url))
else:
    print("No image results returned!")

後續步驟Next steps

另請參閱See also