Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search Bing via Azure API using Python

Tags:

python

azure

bing

How can I search Bing for images using key words?

I am able to search Google using:

import urllib2
import json

credentialGoogle = '' # Google credentials from: https://console.developers.google.com/
searchString = 'Xbox%20One'
top = 20
offset = 0
while offset < top:
    url = 'https://ajax.googleapis.com/ajax/services/search/images?' + \
          'v=1.0&q=%s&start=%d&userip=%s' % (searchString, offset, credentialGoogle)

    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
    results = json.load(response)

    # process results

    offset += 4     # since Google API only returns 4 search results at a time

What would be the equivalent for Bing? Presumably it'd start with:

keyBing = ''        # Bing key from: https://datamarket.azure.com/account/keys
credentialBing = '' # same as key?
searchString = '%27Xbox+One%27'
top = 20
offset = 0

url = 'https://api.datamarket.azure.com/Bing/Search/Image?' + \
      'Query=%s&$top=%d&$skip=%d&$format=json' % (searchString, top, offset)

but how are the credentials set up?

like image 894
jensph Avatar asked Dec 22 '14 16:12

jensph


1 Answers

The Bing equivalent would be:

keyBing = ''        # get Bing key from: https://datamarket.azure.com/account/keys
credentialBing = 'Basic ' + (':%s' % keyBing).encode('base64')[:-1] # the "-1" is to remove the trailing "\n" which encode adds
searchString = '%27Xbox+One%27'
top = 20
offset = 0

url = 'https://api.datamarket.azure.com/Bing/Search/Image?' + \
      'Query=%s&$top=%d&$skip=%d&$format=json' % (searchString, top, offset)

request = urllib2.Request(url)
request.add_header('Authorization', credentialBing)
requestOpener = urllib2.build_opener()
response = requestOpener.open(request) 

results = json.load(response)

# process results

Solution thanks to: http://www.guguncube.com/2771/python-using-the-bing-search-api

like image 108
jensph Avatar answered Sep 21 '22 16:09

jensph