Editar

Partilhar via


Quickstart: Use the Bing Custom Search Python client library

Get started with the Bing Custom Search client library for Python. Follow these steps to install the package and try out the example code for basic tasks. The Bing Custom Search API enables you to create tailored, ad-free search experiences for topics that you care about. The source code for this sample can be found on GitHub.

Use the Bing Custom Search client library for Python to:

  • Find search results on the web from your Bing Custom Search instance.

Reference documentation | Library source code | Package (PyPi) | Samples

Prerequisites

Install the Python client library

Install the Bing Custom Search client library with the following command:

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

Create a new application

Create a new Python file in your favorite editor or IDE, and add the following imports:

from azure.cognitiveservices.search.customsearch import CustomSearchClient
from msrest.authentication import CognitiveServicesCredentials

Create a search client and send a request

  1. Create a variable for your subscription key and endpoint.

    subscription_key = 'your-subscription-key'
    endpoint = 'your-endpoint'
    
  2. Create an instance of CustomSearchClient, using a CognitiveServicesCredentials object with the subscription key.

    client = CustomSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    
  3. Send a search request with client.custom_instance.search(). Append your search term to the query parameter, and set custom_config to your Custom Configuration ID to use your search instance. You can get your ID from the Bing Custom Search portal, by clicking the Production tab.

    web_data = client.custom_instance.search(query="xbox", custom_config="your-configuration-id")
    

View the search results

If any web page search results were found, get the first one and print its name, URL, and total web pages found.

if web_data.web_pages.value:
    first_web_result = web_data.web_pages.value[0]
    print("Web Pages result count: {}".format(len(web_data.web_pages.value)))
    print("First Web Page name: {}".format(first_web_result.name))
    print("First Web Page url: {}".format(first_web_result.url))
else:
    print("Didn't see any web data..")

Next steps