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
- A Bing Custom Search instance. See Quickstart: Create your first Bing Custom Search instance for more information.
- Python 2.x or 3.x.
- The Bing Custom Search SDK for Python.
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
Create a variable for your subscription key and endpoint.
subscription_key = 'your-subscription-key' endpoint = 'your-endpoint'
Create an instance of
CustomSearchClient
, using aCognitiveServicesCredentials
object with the subscription key.client = CustomSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
Send a search request with
client.custom_instance.search()
. Append your search term to thequery
parameter, and setcustom_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..")