Quickstart: Perform a news search with the Bing News Search SDK for Python

Use this quickstart to begin searching for news with the Bing News Search SDK for Python. While Bing News Search has a REST API compatible with most programming languages, the SDK provides an easy way to integrate the service into your applications. The source code for this sample can be found on GitHub.

Prerequisites

It is recommended to use a virtual environment for your python development. You can install and initialize the virtual environment with the venv module. You must install a virtualenv for Python 2.7. You can create a virtual environment with:

python -m venv mytestenv

You can install the Bing News Search SDK dependencies with this command:

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

You must have a Cognitive Services API account with access to the Bing Search APIs. If you don't have an Azure subscription, you can create an account for free. 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. Create a new Python file in your favorite IDE or editor, and import the following libraries. Create a variable for your subscription key, and your search term.

    from azure.cognitiveservices.search.newssearch import NewsSearchAPI
    from msrest.authentication import CognitiveServicesCredentials
    subscription_key = "YOUR-SUBSCRIPTION-KEY"
    search_term = "Quantum Computing"
    

Initialize the client and send a request

  1. Create an instance of CognitiveServicesCredentials. Instantiate the client:

    client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))
    
  2. Send a search query to the News Search API, store the response.

    news_result = client.news.search(query=search_term, market="en-us", count=10)
    

Parse the response

If any search results are found, print the first webpage result:

if news_result.value:
    first_news_result = news_result.value[0]
    print("Total estimated matches value: {}".format(news_result.total_estimated_matches))
    print("News result count: {}".format(len(news_result.value)))
    print("First news name: {}".format(first_news_result.name))
    print("First news url: {}".format(first_news_result.url))
    print("First news description: {}".format(first_news_result.description))
    print("First published time: {}".format(first_news_result.date_published))
    print("First news provider: {}".format(first_news_result.provider[0].name))
else:
    print("Didn't see any news result data..")

Next steps