Editar

Partilhar via


Quickstart: Use the Bing News Search Python client library

Use this quickstart to begin searching for news with the Bing News Search client library for Python. While Bing News Search has a REST API compatible with most programming languages, the client library 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.

Create a virtual environment with:

python -m venv mytestenv

Install the Bing News Search client library dependencies with this command:

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

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 NewsSearchClient
    from msrest.authentication import CognitiveServicesCredentials
    subscription_key = "YOUR-SUBSCRIPTION-KEY"
    endpoint = "YOUR-ENDPOINT"
    search_term = "Quantum Computing"
    

Initialize the client and send a request

  1. Create an instance of CognitiveServicesCredentials.

    client = NewsSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    
  2. Send a search query to the News Search API, and then 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