快速入門:使用適用於 Python 的 Bing Web 搜尋 SDKQuickstart: Use the Bing Web Search SDK for Python

Bing Web 搜尋 SDK 可讓您輕鬆地將 Bing Web 搜尋整合到 Python 應用程式。The Bing Web Search SDK makes it easy to integrate Bing Web Search into your Python application. 在本快速入門中,您將了解如何傳送要求、接收 JSON 回應,以及篩選和剖析結果。In this quickstart, you'll learn how to send a request, receive a JSON response, and filter and parse the results.

要立即查看程式碼嗎?Want to see the code right now? GitHub 上提供適用於 Python 的 Bing Web 搜尋 SDK 範例 (英文)。The Bing Web Search SDK for Python samples are available on GitHub.

本快速入門需要 Azure 認知服務帳戶及 Bing 搜尋 API。This quickstart requires an Azure Cognitive Services account with Bing Search APIs. 如果您還沒有帳戶,可以使用免費試用來取得訂用帳戶金鑰。If you don't have an account, you can use the free trial to get a subscription key.

另請參閱認知服務定價 - Bing 搜尋 APISee also Cognitive Services Pricing - Bing Search API.

必要條件Prerequisites

Bing Web 搜尋 SDK 與 Python 2.7、3.3、3.4、3.5 和 3.6 相容。The Bing Web Search SDK is compatible with Python 2.7, 3.3, 3.4, 3.5, and 3.6. 建議在虛擬環境下使用此快速入門。We recommend using a virtual environment for this quickstart.

  • Python 2.7、3.3、3.4、3.5 或 3.6Python 2.7, 3.3, 3.4, 3.5 or 3.6
  • 適用於 Python 2.7 的 virtualenv (英文)virtualenv for Python 2.7
  • 適用於 Python 3.x 的 venv (英文)venv for Python 3.x

建立及設定您的虛擬環境Create and configure your virtual environment

Python 2.x 和 Python 3.x 在安裝和設定虛擬環境方面各有不同的指示。The instructions to set up and configure a virtual environment are different for Python 2.x and Python 3.x. 請遵循下列步驟來建立和初始化您的虛擬環境。Follow the steps below to create and initialize your virtual environment.

Python 2.xPython 2.x

使用適用於 Python 2.7 的 virtualenv 來建立虛擬環境:Create a virtual environment with virtualenv for Python 2.7:

virtualenv mytestenv

啟動您的環境:Activate your environment:

cd mytestenv
source bin/activate

安裝 Bing Web 搜尋 SDK 相依性:Install Bing Web Search SDK dependencies:

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

Python 3.xPython 3.x

使用適用於 Python 3.x 的 venv 來建立虛擬環境:Create a virtual environment with venv for Python 3.x:

python -m venv mytestenv

安裝 Bing Web 搜尋 SDK 相依性:Install Bing Web Search SDK dependencies:

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

建立用戶端並列印您的第一個結果Create a client and print your first results

既然您已設定虛擬環境並安裝相依性,讓我們來建立用戶端。Now that you've set up your virtual environment and installed dependencies, let's create a client. 用戶端會處理對 Bing Web 搜尋 API 提出的要求及其回應。The client will handle requests to and responses from the Bing Web Search API.

如果回應包含網頁、影像、新聞或影片,則會列印各項的第一個結果。If the response contains web pages, images, news, or videos, the first result for each is printed.

  1. 在您慣用的 IDE 或編輯器建立新的 Python 專案。Create a new Python project using your favorite IDE or editor.

  2. 將此範例程式碼複製到您的專案:Copy this sample code into your project:

    # Import required modules.
    from azure.cognitiveservices.search.websearch import WebSearchAPI
    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 = WebSearchAPI(CognitiveServicesCredentials(subscription_key), base_url = "YOUR_ENDPOINT")
    
    # 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 換成有效的訂用帳戶金鑰。Replace SUBSCRIPTION_KEY with a valid subscription key.

  4. YOUR_ENDPOINT 取代為您在入口網站中的端點 URL。Replace YOUR_ENDPOINT with your endpoint url in portal.

  5. 執行程式。Run the program. 例如: python your_program.pyFor example: python your_program.py.

定義函式和篩選結果Define functions and filter results

既然您已完成第一次呼叫 Bing Web 搜尋 API,讓我們看看一些函式。Now that you've made your first call to the Bing Web Search API, let's look at a few functions. 下列幾節將特別說明可用來改善查詢和篩選結果的 SDK 功能。The following sections highlight SDK functionality for refining queries and filtering results. 每個函式都可以新增至您在上一節所建立的 Python 程式。Each function can be added to the Python program you created in the previous section.

限制 Bing 所傳回的結果數目Limit the number of results returned by Bing

這個範例會使用 countoffset 參數,來限制以 SDK 的 search 方法 (英文) 所傳回的結果數目。This sample uses the count and offset parameters to limit the number of results returned using the SDK's search method. 第一個結果的 nameurl 會列印出來。The name and url for the first result are printed.

  1. 將此程式碼新增至 Python 專案:Add this code to your Python project:

     # 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. 執行程式。Run the program.

篩選新聞及時效性Filter for news and freshness

這個範例會使用 response_filterfreshness 參數,來篩選以 SDK 的 search 方法 (英文) 所傳回的搜尋結果。This sample uses the response_filter and freshness parameters to filter search results using the SDK's search method. 傳回的搜尋結果僅限於 Bing 在過去 24 小時內探索過的新聞文章和網頁。The search results returned are limited to news articles and pages that Bing has discovered within the last 24 hours. 第一個結果的 nameurl 會列印出來。The name and url for the first result are printed.

  1. 將此程式碼新增至 Python 專案:Add this code to your Python project:

    # 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. 執行程式。Run the program.

使用安全搜尋、回應計數和宣傳篩選條件Use safe search, answer count, and the promote filter

這個範例會使用 answer_countpromotesafe_search參數,來篩選以 SDK 的 search 方法 (英文) 所傳回的搜尋結果。This sample uses the answer_count, promote, and safe_search parameters to filter search results using the SDK's search method. 第一個結果的 nameurl 會出現。The name and url for the first result are displayed.

  1. 將此程式碼新增至 Python 專案:Add this code to your Python project:

    # 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. 執行程式。Run the program.

清除資源Clean up resources

此專案使用完畢時,請務必從程式的程式碼中移除訂用帳戶金鑰,並停用虛擬環境。When you're done with this project, make sure to remove your subscription key from the program's code and to deactivate your virtual environment.

後續步驟Next steps

另請參閱See also